package com.szyjjk.controller;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.szyjjk.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.common.collect.Maps;
import com.szyjjk.constants.SzyjjkConstant;
import com.szyjjk.constants.SzyjjkConstantSite;
import com.szyjjk.service.RunFilePathrService;
import com.szyjjk.service.RunMapDataService;
import com.szyjjk.service.RunMapPicService;
import com.szyjjk.service.RunModelFileService;
import com.szyjjk.service.RunModelInfoService;
import com.szyjjk.service.RunSiteService;
import com.szyjjk.service.SysHearWordService;
import com.szyjjk.util.DateUtil;
import com.szyjjk.util.FileUtil;
import com.szyjjk.util.HttpTool;
import com.szyjjk.util.UUIDUtils;


@Controller
@RequestMapping("/Watershed")
public class WatershedModelController {

	@Value("${uploadpath}")
	private String uploadpath;

	private static Logger logger = LoggerFactory.getLogger(WatershedModelController.class);
	@Value("${waterPath}")
	private String waterPath;// 水流域文件位置
	@Value("${waterSBWPath}")
	private String waterSBWPath;
	@Value("${waterNydroPath}")
	private String waterNydroPath;
	@Value("${permanentFilePath}")
	private String permanentFilePath;// 永久存放的文件位置
	@Value("${spareFilePath}")
	private String spareFilePath;// 备用文件文件位置
	@Value("${waterResultPath}")
	private String waterResultPath;// 水流域位置
	@Value("${waterNydroResultPath}")
	private String waterNydroResultPath;// 水动力位置
	@Value("${waterSBWResultPath}")
	private String waterSBWResultPath;// 水质位置
	@Value("${hydroPath}")
	private String hydroPath;// 水质位置
	@Value("${cronstart}")
	private String cronstart;
	@Value("${mapPicPath}")
	private String mapPicPath;
	@Value("${exeMapPicPath}")
	private String exeMapPicPath;
	@Value("${offLine}")
	private Integer offLine;
	@Value("${panfu}")
	private String panfu;
	@Value("${spareFileJpgPath}")
	private String spareFileJpgPath;
	@Value("${dataTh}")
	private String dataTh;
	@Value("${dataThName}")
	private String dataThName;

	@Autowired
	private RunSiteService runSiteService;
	@Autowired
	private RunModelInfoService runModelInfoService;
	@Autowired
	private RunFilePathrService runFilePathrService;
	@Autowired
	private SysHearWordService sysHearWordService;
	@Autowired
	private RunMapPicService runMapPicService;

	@Autowired
	private RunMapDataService runMapDataService;
	@Autowired
	private RunModelFileService runModelFileService;

	public static Map<String, ScheduledFuture<?>> taskmap = Maps.newHashMap();
    public static Map<String, String> modelMap = Maps.newHashMap();
	// 控制输入文件是都读数据库
	public static Map<String, String> modelFileMap = Maps.newHashMap();
	public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
	public static Integer THREAD_END = 1;
	public static Integer THREAD_END1 = 1;
	public static Integer DELFLG = 1;
	public static Integer TIMINGFLG = 1;
	@Autowired
	private ThreadPoolTaskScheduler threadPoolTaskScheduler;

	@InitBinder
	public void initBinder() {
		if (offLine == 1) {
			// 配置文件中的盘符 配置文件中盘符变了 这个也得变
			String f = panfu;
			String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

			String replaceAll = path.replaceAll("/szyjjk-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/", "");
			String panFu = replaceAll.substring(6, replaceAll.length());
			panFu = panFu.replaceAll("/", "\\\\\\\\");
			System.out.println("项目目录---1" + path + "---------" + panFu);
			waterPath = waterPath.replaceAll(f, panFu);
			waterResultPath = waterResultPath.replaceAll(f, panFu);
			waterSBWPath = waterSBWPath.replaceAll(f, panFu);
			waterSBWResultPath = waterSBWResultPath.replaceAll(f, panFu);
			waterNydroPath = waterNydroPath.replaceAll(f, panFu);
			waterNydroResultPath = waterNydroResultPath.replaceAll(f, panFu);
			permanentFilePath = permanentFilePath.replaceAll(f, panFu);
			spareFilePath = spareFilePath.replaceAll(f, panFu);
			hydroPath = hydroPath.replaceAll(f, panFu);
			mapPicPath = mapPicPath.replaceAll(f, panFu);
			exeMapPicPath = exeMapPicPath.replaceAll(f, panFu);
			spareFileJpgPath = spareFileJpgPath.replaceAll(f, panFu);
			dataTh = dataTh.replaceAll(f, panFu);

		}
	}

/*	@RequestMapping("/switch.do")
	@ResponseBody
	public ResponseBo runModel(HttpServletRequest request, String startDateA, String endDateA, String endDate,
			RunModelInfo run, String startDateC, String endDateD) {
		// System.out.println("访问ip---------"+UUIDUtils.getIpAddress(request));

		ResponseBo rb = new ResponseBo();


		*//**
		 * 保存老的源文件 该原文为了新文件提供数据使用
		 *//*
		savaSourceFile();

		if (!"null".equals(startDateA) && !"null".equals(endDateA)) {
			// 不能跨年
			String[] split = startDateA.split("-");
			String[] split1 = endDateA.split("-");

			if (!split[0].equals(split1[0])) {
				rb.setCode(0);
				rb.setMessage("时间段不能跨年");
				return rb;
			}
			run.setStartDate(DateUtil.stringToDate2(startDateA));
			run.setEndDate(DateUtil.stringToDate2(endDateA));
		} else {
			// 没输入年的时候 取今年已有数据替换
			int year = DateUtil.getYear();
			startDateA = year + "-01-01";
			endDateA = year + "-12-31";
			run.setStartDate(DateUtil.stringToDate2(startDateA));
			run.setEndDate(DateUtil.stringToDate2(endDateA));
		}
		String type = run.getType();

		if ("sbw".equals(type) || "all".equals(type) || "timing".equals(type)||"testAuto".equals(type)) {
			
			// 不输入map 范围 取 今天到昨天的范围
			if ("null".equals(startDateC)) {
				startDateC = DateUtil.getNewDateMinusOne();

			}
			if ("null".equals(endDateD)) {
				endDateD = DateUtil.dateToString(new Date());
			}
			if(!endDateD.substring(0, 4).equals(startDateC.substring(0, 4))) {
				startDateC=endDateD.substring(0, 4)+"-01-01";
			}
			if (DateUtil.stringToDate2(startDateC).getTime() > DateUtil.stringToDate2(endDateD).getTime()) {
				rb.setCode(0);
				rb.setMessage("结束时间必须大于开始时间");
				return rb;
			}
			
		}

		run.setLastDate(new Date());
		*//**
		 * 东角头 南山 世界之窗 流域模拟期设置：file.cio文件 气象数据：降雨pcp1.pcp、 温度Tmp1.Tmp、风速wnd.wnd、
		 * 相对湿度hmd.hmd
		 *//*

		String qianZhui = DateUtil.getDate();
		String userid = (String) request.getSession().getAttribute(SzyjjkConstant.TOKEN);
		run.setUserId(userid);
		if (!type.equals("timing")) {
			run.setState(null);
		}
		// TODO 模型开始
		rb.setCode(1);
		isNoReadDataBase();

		if ("water".equals(type)) {
			run.setModelPath(waterResultPath);
			if(StringUtils.isNoneBlank(modelMap.get("water"))) {
				rb.setMessage("水流域模型执行中");
				return rb;
			}
			water(run, type, qianZhui, userid);
			rb.setMessage("水流域执行成功");

		} else if ("nydro".equals(type)) {
			run.setModelPath(waterNydroResultPath);
			if(StringUtils.isNoneBlank(modelMap.get("nydro"))) {
				rb.setMessage("水动力模型执行中");
				return rb;
			}
			nydro(run, type, qianZhui, userid);
			rb.setMessage("水动力执行成功");

		} else if ("sbw".equals(type)) {
			run.setModelPath(waterSBWResultPath);
			if(StringUtils.isNoneBlank(modelMap.get("sbw"))) {
				rb.setMessage("水质模型执行中");
				return rb;
			}
			// 水质所有com开头的文件，放入水质模型的hydro文件
			swb(run, startDateC, endDateD, type, qianZhui, userid, null);
			rb.setMessage("水质执行成功");

		} else if ("all".equals(type)) {
			run.setModelPath(spareFileJpgPath);
			if(StringUtils.isNoneBlank(modelMap.get("water"))) {
				rb.setMessage("水流域模型执行中");
				return rb;
			}
			if(StringUtils.isNoneBlank(modelMap.get("nydro"))) {
				rb.setMessage("水动力模型执行中");
				return rb;
			}
			if(StringUtils.isNoneBlank(modelMap.get("sbw"))) {
				rb.setMessage("水质模型执行中");
				return rb;
			}
			
			water(run, type, qianZhui, userid);
			nydro(run, type, qianZhui, userid);
			swb(run, startDateC, endDateD, type, qianZhui, userid, null);
			rb.setMessage("串联执行成功");

		} else if("dataTh".equals(type)) {
			if(StringUtils.isBlank(modelMap.get("dataTh")) ) {
				Thread th = new Thread(new Runnable() {
					
					@Override
					public void run() {
						modelMap.put("dataTh", "dataTh");
						// yyyy-MM-dd
						//String name ="calibrate.oda";
						*//**
						 * setRunningInGui
						 * F  输入文件路径
						 * name 输入文件名称
						 *//*
						File f = new File(dataTh);
						OpenDaClient.openDaClient(true, f, dataThName);
						modelMap.remove("dataTh");
						try {
							//删除 
							delefdcHis("_efdc.his");
							
							//入库
							String date = DateUtil.getDate();
							String uuid = UUIDUtils.getUUID();
							
							RunFilePath r = new RunFilePath();
							r.setId(uuid);
							r.setCreateTime(new Date());
							r.setFileExId(date);
							r.setFileHz("his");
							r.setFileName(date+"_efdc.his");
							r.setFilePath(dataTh);
							r.setFileSour("dataTh");
							r.setUserId("admin");
							r.setFileRange("2015-01-01_2015-12-31");
							Date str = DateUtil.stringToDate2("2015-01-01");
							Date end = DateUtil.stringToDate2("2015-12-31");
							r.setStrDate(str);
							r.setEndDate(end);
							
							runFilePathrService.insertRunFilePath(r);
							
							sysHearWordService.redBinaryByYear(dataTh+"stochModel\\work2\\efdc.his", uuid);
						
						} catch (Exception e) {
							e.printStackTrace();
						} 
					}

					private void delefdcHis(String end) {
						List<RunFilePath> list1 = runFilePathrService.findByMapAll();
						if(CollectionUtils.isNotEmpty(list1)) {
							for (RunFilePath runFilePath : list1) {
								if(runFilePath.getFileName().endsWith(end)) {
									sysHearWordService.delEfdcById(runFilePath.getId(),"run_his_data_efdc");
									runFilePathrService.delById(runFilePath.getId());
									break;
								}
							}
						}
					}
				});
				th.start();
				
			}else {
				rb.setMessage("数据同化模型执行中");
				return rb;
			}
			rb.setMessage("数据同化模型启动成功");
		} else if ("oneY".equals(type)) {

//			if(StringUtils.isNoneBlank(modelMap.get("water"))) {
//				rb.setMessage("水流域模型执行中");
//				return rb;
//			}
//			if(StringUtils.isNoneBlank(modelMap.get("nydro"))) {
//				rb.setMessage("水动力模型执行中");
//				return rb;
//			}
//			if(StringUtils.isNoneBlank(modelMap.get("sbw"))) {
//				rb.setMessage("水质模型执行中");
//				return rb;
//			}
			
			run.setModelPath(permanentFilePath);
			File f = new File(permanentFilePath+"test.his");
			if(!f.exists()) {
				rb.setMessage(permanentFilePath+"test.his 文件不存在");
				return rb;
			}
			//oneYeatData(run, type, qianZhui, userid);

			if(StringUtils.isBlank(modelMap.get("oneY")) ) {
				Thread th = new Thread(new Runnable() {
					
					@Override
					public void run() {
						modelMap.put("oneY", "oneY");
						try {
						delOneYear("_oneY.his");
						//读取his
						String readHis=permanentFilePath+"test.his";

						//入库
						String date = DateUtil.getDate();
						String uuid = UUIDUtils.getUUID();

						RunFilePath r = new RunFilePath();
						r.setId(uuid);
						r.setCreateTime(new Date());
						r.setFileExId(date);
						r.setFileHz("his");
						r.setFileName(date+"_oneY.his");
						r.setFilePath(readHis);
						r.setFileSour("oneY");
						r.setUserId("admin");
						r.setFileRange("2015-01-01_2015-12-31");
						Date str = DateUtil.stringToDate2("2015-01-01");
						Date end = DateUtil.stringToDate2("2015-12-31");
						r.setStrDate(str);
						r.setEndDate(end);
						
						runFilePathrService.insertRunFilePath(r);
						
						sysHearWordService.redBinaryByOneYear(readHis, uuid);
						modelMap.remove("oneY");
					} catch (Exception e) {
						e.printStackTrace();
						modelMap.remove("oneY");
					} 
				}

					private void delOneYear(String end) {

						List<RunFilePath> list1 = runFilePathrService.findByMapAll();
						if(CollectionUtils.isNotEmpty(list1)) {
							for (RunFilePath runFilePath : list1) {
								if(runFilePath.getFileName().endsWith(end)) {
									sysHearWordService.delEfdcById(runFilePath.getId(),"run_his_data_year");
									runFilePathrService.delById(runFilePath.getId());
									break;
								}
							}
						}
					
						
					}
				});
				th.start();
				
			}else {
				rb.setMessage("一年的his数据读取中");
				return rb;
			}
			rb.setMessage("读取一年的his数据-后台执行中");
		}else if("testAuto".equals(type)) {
			  测试定时任务(startDateC + "_" + endDateD, qianZhui, run);
			
		} else {
			System.out.println("-----------------启动定时任务----------------------------------------");
			// TODO 定时任务
			run.setModelPath(spareFileJpgPath);
			// 自动执行
			run.setExType(1);
			// run.setState(1);
//			// 0 暂停定时任务
//
			if (0 == run.getState()) {
				// 暂停任务
				ScheduledFuture<?> future = taskmap.get(type);
				if (future != null) {
					// 如果参数为true并且任务正在运行，那么这个任务将被取消。
					// 如果参数为false并且任务正在运行，那么这个任务将不会被取消。
					future.cancel(true);
					taskmap.put(type, null);
				}
				rb.setMessage("暂停定时任务成功");
			} else {

				ScheduledFuture<?> future = taskmap.get(type);
				if (future == null) {
					// String cronstart = "0 0 2 * * ?";
					run.setRemarks(cronstart);
					run.setExType(1);
					// 定时任务 执行一个月的+1天
					RunTimeTask runTask = new RunTimeTask(startDateC + "_" + endDateD, run, qianZhui);
					// 每天2点执行
					future = threadPoolTaskScheduler.schedule(runTask, new CronTrigger(cronstart));
					taskmap.put(type, future);
				}
				rb.setMessage("开启定时任务成功");
			}
			if(DELFLG==1) {
			// 删除漏的表数据
			Thread tdel = new Thread(new Runnable() {
				@Override
				public void run() {
					DELFLG=0;
						while(true) {
						System.out.println("启动定时删除任务-删除run_his_data,run_map_data_1-5,run_map_pic,run_map_pic_png中 多余数据"+DateUtil.getDate());
							try {
							Thread.sleep(5*24*60*60*1000);
							sysHearWordService.delNotInRunRilePath();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						
				}
			});tdel.start();
		}
			
		}
		// System.out.println("串联执行结束----------4");
		// 数据来源（执行模型）
		modelMap.remove("switch");
		runModelInfoService.updateById(run);
		return rb;

	}
	*/
	/**
	 * 启动定时任务
	 */
	@RequestMapping(value="/autoToStart.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public void autoToStart() {
		
		List<RunModelInfo> findList = runModelInfoService.findList();
		RunModelInfo run=null;
		for (RunModelInfo runModelInfo : findList) {
			if(runModelInfo.getType().equals("timing")) {
				run=runModelInfo;
				break;
			}
		}
		int  state=run.getState();
		String type=run.getType();
		
		if (1 == state) {
			ScheduledFuture<?> future = taskmap.get(type);
			if (future == null) {
				System.err.println("启动定时任务----------------------------"+new Date());
				// 定时任务 执行一个月的+1天
				RunTimeTask runTask = new RunTimeTask(null, run, null);
				// 每天2点执行
				future = threadPoolTaskScheduler.schedule(runTask, new CronTrigger(cronstart));
				taskmap.put(type, future);
			}		
		} 
	}

	private void oneYeatData(RunModelInfo run, String type, String qianZhui, String userid) {
		if (StringUtils.isBlank(modelMap.get("oneY"))) {
			threadPoolTaskScheduler.createThread(new Runnable() {

				@Override
				public void run() {
					modelMap.put("oneY", "oneY");
					// yyyy-MM-dd
					String startDateC = DateUtil.getYear() + "-01-01";
					String endDateD = DateUtil.getYear() + "-12-31";
					run.setStartDate(DateUtil.stringToDate2(startDateC));
					run.setEndDate(DateUtil.stringToDate2(endDateD));
					// 执行一年的
					water(run, type, qianZhui, userid);
					nydro(run, type, qianZhui, userid);

					swb(run, startDateC, endDateD, type, qianZhui, userid, "2");
					modelMap.remove("oneY");
				}
			});

		}
	}

	private void isNoReadDataBase() {
		List<RunModelFile> fList = runModelFileService.queryList();
		if (CollectionUtils.isNotEmpty(fList)) {
			modelFileMap.clear();
			for (RunModelFile r : fList) {
				// 不需要读取数据库的输入文件
				if (r.getState().equals("1")) {
					modelFileMap.put(r.getFileName(), "1");
				}
			}
		}
	}

	private void swb(RunModelInfo run, String startDateC, String endDateD, String type, String qianZhui, String userid,
			String mapFlg) {
		modelMap.put("sbw", "sbw");
		FileUtil.copyFileComStart(waterNydroResultPath, hydroPath);

		String siteId = SzyjjkConstant.JKOBS_HKA;

		if (StringUtils.isBlank(modelFileMap.get("SBW_2015-radsurf.dat"))) {
			// 该文件暂时不变 取自Ocean model.tem最后一列的辐射
			sBWRadsurf();

		}
		if (StringUtils.isBlank(modelFileMap.get("SBW_2015-wind.dat"))) {
			// 台湾的风
			sBWWind(siteId, run);
		}

		if (StringUtils.isBlank(modelFileMap.get("SBW_river_loads_test2.dat"))) {
			// output.rch 的1234 河 的 每月第一天 的氮磷 (目前只有氮磷)
			sBWRiverLoadsRest();
		}
		/**
		 * 修改产出结果文件的时间范围
		 */
		if (StringUtils.isBlank(modelFileMap.get("test2.inp"))) {
			getTest2Inp(startDateC, endDateD, "test2.inp");
		}
		if (StringUtils.isBlank(modelFileMap.get("test2_r.inp"))) {
			getTest2Inp(startDateC, endDateD, "test2_r.inp");
		}
		
		

		exSBW();

		String mapName = qianZhui + "_" + "test2_r.map";
		String hisName = qianZhui + "_" + "test2_r.his";
		if ("1".equals(mapFlg)) {
			mapName = qianZhui + "_" + "test2_r_oneM.map";
			hisName = qianZhui + "_" + "test2_r_oneM.his";
		}
		if ("2".equals(mapFlg)) {
			mapName = qianZhui + "_" + "test2_r_oneY.map";
			hisName = qianZhui + "_" + "test2_r_oneY.his";
			FileUtil.copyFile3(waterSBWResultPath + "test2_r.map", permanentFilePath, mapName);
		}
		FileUtil.copyFile1(waterSBWResultPath + "test2_r-bal.his", permanentFilePath, qianZhui + "_");
		// FileUtil.copyFile1(waterSBWResultPath + "test2_r.map",
		// permanentFilePath,qianZhui + "_");
		FileUtil.copyFile3(waterSBWResultPath + "test2_r.his", permanentFilePath, hisName);
		saveRunFilePath(qianZhui, "map", mapName, type, userid, startDateC + "_" + endDateD);
		saveRunFilePath(qianZhui, "his", hisName, type, userid, startDateC + "_" + endDateD);
		//saveRunFilePath(qianZhui, "bal.his", qianZhui + "_" + "test2_r-bal.his", type, userid,
		//		startDateC + "_" + endDateD);
		// System.out.println("串联执行结束----------2");
		modelMap.remove("sbw");
	}

	private void nydro(RunModelInfo run, String type, String qianZhui, String userid) {
		modelMap.put("nydro", "水动力执行中");

		/**
		 * 水动力 使用香港天文台数据 hka 香港国际机场 5V3PAOAB07091DN39WG9SC4KQ65NZN5K 统一删除该文件 然后新增
		 */
		String siteId = SzyjjkConstant.JKOBS_HKA;
		if (StringUtils.isBlank(modelFileMap.get("wnd.wnd"))) {
			// 风
			bigWnd(siteId, run);
		}
		if (StringUtils.isBlank(modelFileMap.get("Ocean model.tem"))) {
			oceanModel(siteId, run);
		}
		if (StringUtils.isBlank(modelFileMap.get("szb.dis"))) {
			szbDis();
		}

		exNydro();
		FileUtil.copyFile1(waterNydroResultPath + "trih-szb.dat", permanentFilePath, qianZhui + "_");
		FileUtil.copyFile1(waterNydroResultPath + "trim-szb.dat", permanentFilePath, qianZhui + "_");
		//saveRunFilePath(qianZhui, "dat", qianZhui + "_" + "trih-szb.dat", type, userid, null);
		//saveRunFilePath(qianZhui, "dat", qianZhui + "_" + "trim-szb.dat", type, userid, null);
		modelMap.remove("nydro");
	}

	private void water(RunModelInfo run, String type, String qianZhui, String userid) {
		modelMap.put("water", "water");
//		List<String> siteList = SzyjjkConstant.SITELIST;
//		List<String> siteList1 = SzyjjkConstant.SITELIST1;
		String dateType = SzyjjkConstant.DATETYPE;
		String dateType1 = SzyjjkConstant.DATETYPE1;
		String dateType2 = SzyjjkConstant.DATETYPE2;
		String dateType3 = SzyjjkConstant.DATETYPE3;

		List<String> siteList = SzyjjkConstant.WATER;
		// 没上传 自己编辑
		if (StringUtils.isBlank(modelFileMap.get("file.cio"))) {
			// file.cio 该2020
			inputFile();

		}
		if (StringUtils.isBlank(modelFileMap.get("wnd.wnd"))) {
			// 风速wnd
			inputWnd(siteList, dateType, run);

		}
		// System.out.println("----------");
		if (StringUtils.isBlank(modelFileMap.get("pcp1.pcp"))) {
			// 降水psp
			inputPcp(siteList, dateType1, run);

		}

		if (StringUtils.isBlank(modelFileMap.get("hmd.hmd"))) {
			// 相对湿度hmd
			inputHmd(siteList, dateType2, run);
		}

		if (StringUtils.isBlank(modelFileMap.get("Tmp1.Tmp"))) {
			// 气温 tmp
			inputTmp(siteList, dateType3, run);
		}

//		if (StringUtils.isBlank(modelMap.get("44p.dat"))) {
//			modelMap.remove("44p.dat");
//			// 44p 该文件只是把2015年复制一份放置2020年
//			input44p(siteList, dateType3, run);
//		}

		exWater();
		// 永久保存这个文件 output.rch
		FileUtil.copyFile1(waterResultPath + "output.rch", permanentFilePath, qianZhui + "_");
		// 河流
		//saveRunFilePath(qianZhui, "rch", qianZhui + "_" + "output.rch", type, userid, null);
		modelMap.remove("water");
	}

	private void input44p(List<String> siteList, String dateType3, RunModelInfo run) {
		// 旧文件
		String pathOld = spareFilePath + "44p.dat";
		String pathNew = waterResultPath + "44p.dat";

		int year = DateUtil.getYear();
		String[] fileContent = FileUtil.getFileContent(pathNew);
		// 当前文件没有今年数据 增加今年数据
		if (!(fileContent[0].contains(year + ""))) {
			// 备用文件91行是2015年第一月数据
			StringBuilder sb = new StringBuilder();
			for (int i = 91; i <= 102; i++) {
				String fileContent5 = FileUtil.getFileContent5(pathOld, i);
				String data = fileContent5.replaceAll("2015", year + "");
				sb.append(data);
				sb.append("\n");
			}
			FileUtil.appendContent(pathNew, sb.toString());
		}
	}

	private void inputFile() {
		// F:\WateraModels\TxtInOut
		String pathN = waterResultPath + "file.cio";
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i < 86; i++) {
			String fileContent6 = FileUtil.getFileContent5(pathN, i);
			// System.out.println(fileContent6);
			if (i == 9) {
				fileContent6 = fileContent6.replace("2015", DateUtil.getYear() + "");
			}
			sb.append(fileContent6);
			sb.append("\n");
		}
		FileUtil.createFileOrWrite(pathN, sb.toString());

	}

	private void saveRunFilePath(String qianZhui, String houZhui, String FileName, String model, String userId,
			String fileRange) {
		RunFilePath r = new RunFilePath();
		String uuid = UUIDUtils.getUUID();
		r.setId(uuid);
		r.setCreateTime(new Date());
		r.setFileExId(qianZhui);
		r.setFileHz(houZhui);
		r.setFileName(FileName);
		r.setFilePath(permanentFilePath);
		r.setFileSour(model);
		r.setUserId(userId);
		r.setFileRange(fileRange);
		if (StringUtils.isNotBlank(fileRange)) {
			String[] split = fileRange.split("_");
			Date str = DateUtil.stringToDate2(split[0]);
			Date end = DateUtil.stringToDate2(split[1]);
			r.setStrDate(str);
			r.setEndDate(end);
		}
		runFilePathrService.insertRunFilePath(r);
		
		if ("his".equals(houZhui)) {
			// his 转数据线程
			String[] split1 = fileRange.split("_");
			String date1=split1[0];
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						
						sysHearWordService.redBinary(permanentFilePath + FileName, r.getId(),date1);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			});
			t.start();

		} else if ("map".equals(houZhui)) {
			String[] split1 = fileRange.split("_");
			String date1=split1[0];
			// 如果是自动东西 删除上一次map
			if (FileName.endsWith("oneM.map")) {
				delLastTime(FileName);
			}
			
			// map 转数据 线程
			Thread tt = new Thread(new Runnable() {

				@Override
				public void run() {
					TIMINGFLG=0;
					// System.out.println("map数据开始---------------------------");
					try {
						// String path = r.getFilePath() + r.getFileName();
						String path = waterSBWResultPath + "test2_r.map";
						// String path="E:\\WateraModels\\test2_r.map";
						DecimalFormat df1 = new DecimalFormat("#########.####");
						DecimalFormat df = new DecimalFormat("#########.#");
						DataInputStream dis = null;

						// test2.his: true
						// test2.map: false
						dis = new DataInputStream(new FileInputStream(path));

						dis.skip(124);

						byte[] bParamNameTime = new byte[19];
						String sParamNameTime = "";
						dis.read(bParamNameTime);
						sParamNameTime = new String(bParamNameTime);
						Date beginTime = null;
						try {
							beginTime = HttpTool.BinarySimpDate.parse(sParamNameTime);
						} catch (Exception e) {
							e.printStackTrace();
						}

						// System.out.println(beginTime);

						dis.skip(17);

						byte[] bVarBUf = new byte[4];
						dis.read(bVarBUf);
						int iParamSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
						// .out.println(iParamSize);

						dis.read(bVarBUf);
						int iLocationSize = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
						// System.out.println(iLocationSize);

						StringBuilder sb = new StringBuilder();
						byte[] bParamName = new byte[20];
						String[] sParamName = new String[iParamSize];
						for (int i = 0; i < iParamSize; i++) {
							dis.read(bParamName);
							sParamName[i] = new String(bParamName);
							sb.append(sParamName[i]);
						}
						String[] proArrayList = sb.toString().split("          ");
						// System.out.println(sb.toString());

						String[] sLocationName = new String[iLocationSize];
						for (int i = 0; i < iLocationSize; i++) {
							sLocationName[i] = "segment " + df1.format(i + 1);
						}
						// 判断属性名是否在 字典内
						List<RunProperty> findProAll = sysHearWordService.findProAll();

						if (CollectionUtils.isEmpty(findProAll)) {
							return;
						}
						// 获取需要的元素名称
						Map<String, RunProperty> mmm = new HashMap<>();
						for (RunProperty runProperty : findProAll) {
							if (StringUtils.isBlank(runProperty.getProRemark())) {
								continue;
							}
							mmm.put(runProperty.getProRemark(), runProperty);
						}

						List<RunMapData> list = new ArrayList<>();

						while (dis.available() > 0) {
							dis.read(bVarBUf);
							int secound = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getInt();
							Calendar calendar = Calendar.getInstance();
							calendar.setTime(beginTime);
							calendar.add(Calendar.SECOND, secound);

							Calendar date = Calendar.getInstance();
							date.setTime(DateUtil.stringToDate2(date1));
							calendar.set(Calendar.YEAR, date.get(Calendar.YEAR));
							// 元素时间
							Date time = calendar.getTime();
							// System.out.println("---------------"+DateUtil.dateToString2(time));

							// 站点 一个时间的站点
							for (int i = 0; i < iLocationSize; i++) {
								String site = sLocationName[i];
								// System.out.println("---------------"+DateUtil.dateToString2(time));

								RunMapData rmd = new RunMapData();
								rmd.setId(UUIDUtils.getUUID());
								rmd.setCreateTime(new Date());
								rmd.setMapId(r.getId());
								rmd.setMapSite(site);
								int siteHao = (i + 1) % 520;
								if (siteHao == 0) {
									siteHao = 520;
								}

								rmd.setMapSiteXy(SzyjjkConstantSite.SITE.get(siteHao + ""));
								rmd.setMapTime(time);

								// 元素 量 104
								for (int j = 0; j < iParamSize; j++) {
									dis.read(bVarBUf);
									double values = ByteBuffer.wrap(bVarBUf).order(ByteOrder.LITTLE_ENDIAN).getFloat();
									String fiName = proArrayList[j].replaceAll(" ", "");
									//System.err.println(fiName);
									if(fiName.equals("SecchiDept")) {
										fiName="Transparence";
									}
									if (mmm.get(fiName) == null) {
										continue;
									}
									if (fiName.equals("TotP")) {
										rmd.setTotp(df.format(values));
									} else if (fiName.equals("PO4")) {
										rmd.setPo4(df.format(values));
									} else if (fiName.equals("Turbidity")) {
										rmd.setTurbidity(df.format(values));
									} else if (fiName.equals("EnCoc")) {
										if(values!=0) {
											values=Math.log10(values);
										}
										rmd.setEncoc(df.format(values));
									} else if (fiName.equals("EnCoc")) {
										rmd.setEncoc(df.format(values));
									} else if (fiName.equals("Temp")) {
										rmd.setTemp(df.format(values));
									} else if (fiName.equals("NH4")) {
										rmd.setNh4(df.format(values));
									} else if (fiName.equals("SS")) {
										rmd.setSs(df.format(values));
									} else if (fiName.equals("FColi")) {
										if(values!=0) {
											values=Math.log10(values);
										}
										rmd.setFcoli(df.format(values));
									} else if ("Transparence".equals(fiName)) {
										rmd.setTransparence(df.format(values));
									} else if (fiName.equals("KjelN")) {
										rmd.setKjeln(df.format(values));
									} else if (fiName.equals("PH")) {
										rmd.setPh(df.format(values));
									} else if (fiName.equals("EColi")) {
										if(values!=0) {
											values=Math.log10(values);
										}
										rmd.setEcoli(df.format(values));
									} else if (fiName.equals("BOD")) {
										rmd.setBod(df.format(values));
									} else if (fiName.equals("OXY")) {
										rmd.setOxy(df.format(values));
									} else if (fiName.equals("TotN")) {
										rmd.setTotn(df.format(values));
									} else if (fiName.equals("TOC")) {
										rmd.setToc(df.format(values));
										rmd.setBod(df.format(values*0.63));
									} else if (fiName.equals("NO3")) {
										rmd.setNo3(df.format(values));
									} else if (fiName.equals("Salinity")) {
										rmd.setSalinity(df.format(values));
									} else if (fiName.equals("Chlfa")) {
										rmd.setChlfa(df.format(values));
									}
								}
								list.add(rmd);

								String mapLayer = null;
								int c = i + 1;
								
								if (c == 520) {
									// 1 层
									mapLayer = "run_map_data_1";
									runMapDataService.insertList(list, mapLayer);
									list.clear();
								} else if (c == 1040) {
									mapLayer = "run_map_data_2";
									runMapDataService.insertList(list, mapLayer);
									list.clear();
								} else if (c == 1560) {
									mapLayer = "run_map_data_3";
									runMapDataService.insertList(list, mapLayer);
									list.clear();
								} else if (c == 2080) {
									mapLayer = "run_map_data_4";
									runMapDataService.insertList(list, mapLayer);
									list.clear();
								} else if (c == 2600) {
									mapLayer = "run_map_data_5";
									runMapDataService.insertList(list, mapLayer);
									list.clear();
								}
							}
						}
						dis.close();
					} catch (Exception e) {
						TIMINGFLG=1;
						e.printStackTrace();
					}
					 System.out.println("map数据结束---------------------------");
					 TIMINGFLG=1;
				}
			});
			tt.start();

			
			
			// map 转png 线程
			Thread ttt = new Thread(new Runnable() {

				@Override
				public void run() {
					mapZPng(fileRange, r);
					//mapZJpg(fileRange, r); 次方法放在 mapZPng中 jpg转png 步骤前 启动线程执行
				}

				private void mapZPng(String fileRange, RunFilePath r) {
					System.out.println("启动线程    制作渲染图片png");
					try {
						if (THREAD_END1 == 0) {
							while (true) {
								Thread.sleep(60000);
								if (THREAD_END1 == 1) {
									break;
								}
							}
						}
						// 开启临时锁
						THREAD_END1 = 0;
						String cco = hydroPath + "com.cco";
						String jpg = spareFileJpgPath + "JPG\\"
								+ r.getFileName().substring(0, r.getFileName().length() - 4) + "_PNG\\";
						String mapParam = mapPicPath + "RunTestPng.m";
						List<RunProperty> findProAll = sysHearWordService.findProAll();

						StringBuilder sb = new StringBuilder();
						sb.append("d3d_qp('openfile','" + waterSBWResultPath + "test2_r.map" + "','" + cco + "');");
//						sb.append("d3d_qp('selectfield','grid');");
//						sb.append("d3d_qp('quickview');");
//						sb.append("d3d_qp('axeslimits');");
						List<RunMapPic> listRun = new ArrayList<>();
						for (RunProperty runProperty : findProAll) {

							// 浑浊度 透明度 生物需氧量 暂无 跳过

							String code = runProperty.getProRemark();
							if (StringUtils.isBlank(code)) {
								continue;
							}
							// .
							if (code.equals("Turbidity")) {
								continue;
							}
//							if (code.equals("Transparence")) {
//								continue;
//							}
							if (code.equals("BOD")) {
								continue;
							}
							sb.append("d3d_qp('selectfield','grid');");
							sb.append("d3d_qp('quickview');");
							sb.append("d3d_qp('axeslimits');");
							String[] split = fileRange.split("_");
							String touDate = split[0] + " 00:00:00";
							String weiDate = split[1] + " 00:00:00";
							Date touDateD = DateUtil.stringToDate3(touDate);
							Date weiDateD = DateUtil.stringToDate3(weiDate);

							// 计算 当前时间到头时间有多少值
							int dayNum = (DateUtil.getDayNum(touDateD, weiDateD));
							// 文件中小时的标记
							int fileNo = (dayNum * 24) + 1;
							if("Transparence".equals(code)) {
								code="SecchiDept";
							}
							sb.append("d3d_qp('selectfield','" + code + "');");
							sb.append("d3d_qp('allm',1);");
							sb.append("d3d_qp('alln',1);");
							sb.append("d3d_qp('allk',0);");
							// 去掉图例

							sb.append("d3d_qp('colourbar',0);");
							// 标题为空
							sb.append("d3d_qp('title','');");

							// X轴标题为空
							sb.append("d3d_qp('xlabel','');");

							// Y轴标题为空
							sb.append("d3d_qp('ylabel','');");

							// X轴颜色
							sb.append("d3d_qp('xcolour', [ 0.9999 0.9999 0.9999 ]);");

							// Y轴颜色
							sb.append("d3d_qp('ycolour', [ 0.9999 0.9999 0.9999 ]);");
							sb.append("d3d_qp('addtoplot');");
							// RunTest_bat.m 的全路径
							String picTou = code + "_" + DateUtil.getDate();
							String pic = null;
							String pic1 = null;
							for (int i = 0; i < fileNo; i++) {
								Date date = DateUtil.addDateMinut(touDateD, i);
								pic = picTou + "_" + i + ".jpg";
								pic1 = picTou + "_" + i + ".png";
								RunMapPic rmp = new RunMapPic();
								rmp.setId(UUIDUtils.getUUID());
								rmp.setFileid(r.getId());
								rmp.setMapName(r.getFileName());
								rmp.setMapPath(r.getFilePath());
								rmp.setCcoPath(cco);
								rmp.setParamPath(mapParam);
								rmp.setMapValue(code);
								rmp.setMapCode(code);
								rmp.setMapDate(i + "");
								rmp.setMapTime(date);
								rmp.setCreateTime(new Date());
								/**
								 * 存入库的图片名称和实际的不一样 实际的图片jpg 需要转png
								 */
								rmp.setMapPicName(pic1);
								rmp.setMapPicPath(jpg);
								rmp.setRemake("0");
								listRun.add(rmp);
								sb.append("d3d_qp('slider',0," + i + ");");
								sb.append("d3d_qp('printfigure','" + rmp.getMapPicPath() + pic
										+ "','JPG file', 2, 150, 1, 1, 1);");
							}

						}
						sb.append("d3d_qp('closefigure');");
						sb.append("d3d_qp('closefile');");
						sb.append("d3d_qp('close');");

						File f = new File(jpg);
						if (!f.exists()) {
							f.mkdirs();
						}
						FileUtil.createFileOrWrite(mapParam, sb.toString());
						String cmd = exeMapPicPath + "  " + mapParam;
						Runtime rn = Runtime.getRuntime();
						rn.exec(cmd);

						for (RunMapPic runMapPic : listRun) {
							runMapPicService.insertRunFilePathPng(runMapPic);
						}
						// 判断是都生成了 listRun。size个图片 如果生成了 处理这些图片 然后删除

						while (true) {
							try {
								Thread.sleep(1000 * 60);
							} catch (Exception e) {
								e.printStackTrace();
							}

							File fPng = new File(jpg);
							File[] listFiles = fPng.listFiles();
							if (listFiles == null) {
								continue;
							}
							// 生成图片未结束
							if (listFiles.length != listRun.size()) {
								continue;
							}
							//需要jpg转png的图片制作完成 线程新线程 制作渲染图片 jpg
							Thread thr = new Thread(new Runnable() {
								
								@Override
								public void run() {
									System.out.println("启动线程    制作渲染图片jpg");
									mapZJpg(fileRange, r); 
								}
							});  thr.start();
							
							//开始转换图片 jpg转png
							for (int i = 0; i < listFiles.length; i++) {
								String name = listFiles[i].getName();
								String newName = name.substring(0, name.length() - 3) + "png";
								FileUtil.jpgZhuanPng(jpg + name, jpg + newName);
								FileUtil.delFile(jpg + name);
								System.out.println("总数量:" + listFiles.length + "--当前执行位置:" + (i+1) + "--正在转换的图片名:" + name);
							}
							break;
						}
						// 关闭临时锁
						THREAD_END1 = 1;
					} catch (Exception e) {
						e.printStackTrace();
						THREAD_END1 = 1;
					}
				}

				private void mapZJpg(String fileRange, RunFilePath r) {
					try {
						if (THREAD_END == 0) {
							while (true) {
								Thread.sleep(60000);
								if (THREAD_END == 1) {
									break;
								}
							}
						}
						// 开启临时锁
						THREAD_END = 0;
						String cco = hydroPath + "com.cco";
						String jpg = spareFileJpgPath + "JPG\\"
								+ r.getFileName().substring(0, r.getFileName().length() - 4) + "\\";
						String mapParam = mapPicPath + "RunTest.m";
						List<RunProperty> findProAll = sysHearWordService.findProAll();

						StringBuilder sb = new StringBuilder();
						sb.append("d3d_qp('openfile','" + waterSBWResultPath + "test2_r.map" + "','" + cco + "');");
//						sb.append("d3d_qp('selectfield','grid');");
//						sb.append("d3d_qp('quickview');");
//						sb.append("d3d_qp('axeslimits');");
						List<RunMapPic> listRun = new ArrayList<>();
						for (RunProperty runProperty : findProAll) {
							String proRemark = runProperty.getProRemark();
							if (StringUtils.isBlank(proRemark)) {
								continue;
							}

							// 浑浊度 透明度 生物需氧量 暂无 跳过

							String code = runProperty.getProRemark();
							if (StringUtils.isBlank(code)) {
								continue;
							}
							// .
							if (code.equals("Turbidity")) {
								continue;
							}
//							if (code.equals("Transparence")) {
//								continue;
//							}
							if (code.equals("BOD")) {
								continue;
							}
							sb.append("d3d_qp('selectfield','grid');");
							sb.append("d3d_qp('quickview');");
							sb.append("d3d_qp('axeslimits');");
							
							String[] split = fileRange.split("_");
							String touDate = split[0] + " 00:00:00";
							String weiDate = split[1] + " 00:00:00";
							Date touDateD = DateUtil.stringToDate3(touDate);
							Date weiDateD = DateUtil.stringToDate3(weiDate);

							// 计算 当前时间到头时间有多少值
							int dayNum = (DateUtil.getDayNum(touDateD, weiDateD));
							// 文件中小时的标记
							int fileNo = (dayNum * 24) + 1;

							sb.append("d3d_qp('selectfield','" + code + "');");
							sb.append("d3d_qp('allm',1);");
							sb.append("d3d_qp('alln',1);");
							sb.append("d3d_qp('allk',0);");
							sb.append("d3d_qp('addtoplot');");
							// RunTest_bat.m 的全路径
							String picTou = code + "_" + DateUtil.getDate();
							String pic = null;

							for (int i = 0; i < fileNo; i++) {
								Date date = DateUtil.addDateMinut(touDateD, i);
								pic = picTou + "_" + i + ".jpg";
								RunMapPic rmp = new RunMapPic();
								rmp.setId(UUIDUtils.getUUID());
								rmp.setFileid(r.getId());
								rmp.setMapName(r.getFileName());
								rmp.setMapPath(r.getFilePath());
								rmp.setCcoPath(cco);
								rmp.setParamPath(mapParam);
								rmp.setMapValue(code);
								rmp.setMapCode(code);
								rmp.setMapDate(i + "");
								rmp.setMapTime(date);
								rmp.setCreateTime(new Date());
								rmp.setMapPicName(pic);
								rmp.setMapPicPath(jpg);
								rmp.setRemake("0");
								listRun.add(rmp);
								sb.append("d3d_qp('slider',0," + i + ");");
								sb.append("d3d_qp('printfigure','" + rmp.getMapPicPath() + rmp.getMapPicName()
										+ "','JPG file', 2, 150, 1, 1, 1);");
							}

						}
						sb.append("d3d_qp('closefigure');");
						sb.append("d3d_qp('closefile');");
						sb.append("d3d_qp('close');");

						File f = new File(jpg);
						if (!f.exists()) {
							f.mkdirs();
						}
						FileUtil.createFileOrWrite(mapParam, sb.toString());
						String cmd = exeMapPicPath + "  " + mapParam;
						Runtime rn = Runtime.getRuntime();
						rn.exec(cmd);

						for (RunMapPic runMapPic : listRun) {
							runMapPicService.insertRunFilePath(runMapPic);
						}

						// 关闭临时锁
						THREAD_END = 1;
					} catch (Exception e) {
						e.printStackTrace();
						THREAD_END = 1;
					}
				}
			});
			ttt.start();

			// map 转jpg图片线程
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						if (THREAD_END == 0) {
							while (true) {
								Thread.sleep(60000);
								if (THREAD_END == 1) {
									break;
								}
							}
						}
						// 开启临时锁
						THREAD_END = 0;
						String cco = hydroPath + "com.cco";
						String jpg = spareFileJpgPath + "JPG\\"
								+ r.getFileName().substring(0, r.getFileName().length() - 4) + "\\";
						String mapParam = mapPicPath + "RunTest.m";
						List<RunProperty> findProAll = sysHearWordService.findProAll();

						StringBuilder sb = new StringBuilder();
						sb.append("d3d_qp('openfile','" + waterSBWResultPath + "test2_r.map" + "','" + cco + "');");
						sb.append("d3d_qp('selectfield','grid');");
						sb.append("d3d_qp('quickview');");
						sb.append("d3d_qp('axeslimits');");
						List<RunMapPic> listRun = new ArrayList<>();
						for (RunProperty runProperty : findProAll) {
							String proRemark = runProperty.getProRemark();
							if (StringUtils.isBlank(proRemark)) {
								continue;
							}
							// 浑浊度 透明度 生物需氧量 暂无 跳过
							if ("Turbidity".equals(proRemark) || "Transparence".equals(proRemark)
									|| "BOD".equals(proRemark)) {
								continue;
							}
							String code = runProperty.getProRemark();
							// .
							if (code.equals("Turbidity")) {
								continue;
							}
							if (code.equals("Transparence")) {
								continue;
							}
							if (code.equals("BOD")) {
								continue;
							}
							String[] split = fileRange.split("_");
							String touDate = split[0] + " 00:00:00";
							String weiDate = split[1] + " 00:00:00";
							Date touDateD = DateUtil.stringToDate3(touDate);
							Date weiDateD = DateUtil.stringToDate3(weiDate);

							// 计算 当前时间到头时间有多少值
							int dayNum = (DateUtil.getDayNum(touDateD, weiDateD));
							// 文件中小时的标记
							int fileNo = (dayNum * 24) + 1;

							sb.append("d3d_qp('selectfield','" + code + "');");
							sb.append("d3d_qp('allm',1);");
							sb.append("d3d_qp('alln',1);");
							sb.append("d3d_qp('allk',0);");
							sb.append("d3d_qp('addtoplot');");
							// RunTest_bat.m 的全路径
							String picTou = code + "_" + DateUtil.getDate();
							String pic = null;

							for (int i = 0; i < fileNo; i++) {
								Date date = DateUtil.addDateMinut(touDateD, i);
								pic = picTou + "_" + i + ".jpg";
								RunMapPic rmp = new RunMapPic();
								rmp.setId(UUIDUtils.getUUID());
								rmp.setFileid(r.getId());
								rmp.setMapName(r.getFileName());
								rmp.setMapPath(r.getFilePath());
								rmp.setCcoPath(cco);
								rmp.setParamPath(mapParam);
								rmp.setMapValue(code);
								rmp.setMapCode(code);
								rmp.setMapDate(i + "");
								rmp.setMapTime(date);
								rmp.setCreateTime(new Date());
								rmp.setMapPicName(pic);
								rmp.setMapPicPath(jpg);
								rmp.setRemake("0");
								listRun.add(rmp);
								sb.append("d3d_qp('slider',0," + i + ");");
								sb.append("d3d_qp('printfigure','" + rmp.getMapPicPath() + rmp.getMapPicName()
										+ "','JPG file', 2, 150, 1, 1, 1);");
							}

						}
						sb.append("d3d_qp('closefigure');");
						sb.append("d3d_qp('closefile');");
						sb.append("d3d_qp('close');");

						File f = new File(jpg);
						if (!f.exists()) {
							f.mkdirs();
						}
						FileUtil.createFileOrWrite(mapParam, sb.toString());
						String cmd = exeMapPicPath + "  " + mapParam;
						Runtime rn = Runtime.getRuntime();
						rn.exec(cmd);

						for (RunMapPic runMapPic : listRun) {
							runMapPicService.insertRunFilePath(runMapPic);
						}

						// 关闭临时锁
						THREAD_END = 1;
					} catch (Exception e) {
						e.printStackTrace();
						THREAD_END = 1;
					}

				}
			});
			// t.start();

		}
		// System.out.println("串联执行结束----------3");
	}

	private void delLastTime(String fileName2) {
		// 20201009173341_test2_r_oneM.map

//		List<String> listDelMap = new ArrayList<>();
		
//		List<String> listEx = new ArrayList<>();
		List<RunFilePath> list = runFilePathrService.findByMap();
		if (CollectionUtils.isNotEmpty(list)) {
			//删除map 相关数据
			for (RunFilePath runFilePath : list) {

				String fileName = runFilePath.getFileName();
				// 删除上次执行的 本次执行的跳过
				if (fileName2.equals(fileName)) {
					continue;
				}
				//listEx.add(runFilePath.getFileExId());
				if("map".equals(runFilePath.getFileHz())) {
//					listDelMap.add(runFilePath.getId());
					// 删除map数据库数据 5 个表
					runMapDataService.deleteByMapId(runFilePath.getId());
					// 删除 pic
					List<RunMapPic> findByMapName2 = runMapPicService.findByMapName(fileName);
					if (CollectionUtils.isNotEmpty(findByMapName2)) {

						FileUtil.deleteFiles(findByMapName2.get(0).getMapPicPath());
						File f = new File(findByMapName2.get(0).getMapPicPath());
						if (f.exists()) {
							f.delete();
						}

						runMapPicService.delByMapName(fileName);
					}
					// 删除png

					List<RunMapPic> findByMapName3 = runMapPicService.findByMapNamePng(fileName);
					if (CollectionUtils.isNotEmpty(findByMapName3)) {

						FileUtil.deleteFiles(findByMapName3.get(0).getMapPicPath());
						File f = new File(findByMapName3.get(0).getMapPicPath());
						if (f.exists()) {
							f.delete();
						}
						runMapPicService.delByMapNamePng(fileName);
					}
				}

				runFilePathrService.delById(runFilePath.getId());
			}

			// 删除其他文件
			List<RunFilePath> list1 = runFilePathrService.findByMapAll();
			if (CollectionUtils.isNotEmpty(list1)) {
				for (RunFilePath runFilePath : list1) {
//					String fileExId = runFilePath.getFileExId();
//					if (listEx.contains(fileExId)) {
//						runFilePathrService.delById(runFilePath.getId());
//						File f = new File(runFilePath.getFilePath() + runFilePath.getFileName());
//						f.delete();
//					}
					// 删除his
					if (runFilePath.getFileName().contains("oneM.his")) {
						//不是本次执行得his
						if (!fileName2.substring(0, 14).equals(runFilePath.getFileName().substring(0, 14))) {
							Integer delById = sysHearWordService.delById(runFilePath.getId());
							System.out.println("删除前天his数据,id:" + runFilePath.getId() + "--删除量:" + delById);
							if (delById > 0) {
								runFilePathrService.delById(runFilePath.getId());
							}
						}
					}
				}
			}
		}
	}

	private void getTest2Inp(String startDateC, String endDateD, String fileName) {
		int row = 1;
		while (true) {
			String fileContent5 = FileUtil.getFileContent5(spareFilePath + fileName, row);
			if (row == 1) {
				String substring = fileContent5.substring(0, fileContent5.length());
				substring = substring + "\r\n" + ";" + "\r\n";
				FileUtil.createFileOrWrite(waterSBWResultPath + fileName, substring);
				row += 2;
				continue;
			}

			// 开始时间 把年转化成2015
			// 2015/01/01-00:00:00 ; start time
			if (row == 83) {
				String[] cArray = startDateC.split("-");
				StringBuilder sb = new StringBuilder();
				String[] split = fileContent5.split("\\/");
				sb.append(split[0]).append("/").append(cArray[1]).append("/").append(cArray[2])
						.append(split[2].substring(2, split[2].length()));
				fileContent5 = sb.toString();
			}
			// 结束时间
			if (row == 84) {
				String[] cArray = endDateD.split("-");
				StringBuilder sb = new StringBuilder();
				String[] split = fileContent5.split("\\/");
				sb.append(split[0]).append("/").append(cArray[1]).append("/").append(cArray[2])
						.append(split[2].substring(2, split[2].length()));
				fileContent5 = sb.toString();
			}

			FileUtil.appendContent(waterSBWResultPath + fileName, fileContent5);
			if (fileName.startsWith("test2_r")) {
				if (row == 279) {
					break;
				}
			} else {
				if (row == 272) {
					break;
				}
			}

			row++;
		}
	}

	private void sBWRiverLoadsRest() {
		// 生成文件年份数据变更
		@SuppressWarnings("all")
		String year = DateUtil.getYear() + "";
		logger.info("SBW_river_loads_test2.dat-------------------------" + new Date());
		String filePath = waterResultPath + "output.rch";
		// 每月一号 可能提取
		List<Integer> actualMaximum = DateUtil.actualMaximum(2015);
		List<String> monthOfDay = new ArrayList<>();
		monthOfDay.add("1");

		for (int b = 0; b < actualMaximum.size() - 1; b++) {
			Integer integer = actualMaximum.get(b);//
			String string = monthOfDay.get(b);
			monthOfDay.add((integer + integer.parseInt(string)) + "");
		}
//		List<String> monthOfDay = Arrays.asList("1", "31", "61", "91", "121", "151", "181", "211", "241", "271", "301",
//				"331");
		// key 1234 河流 list1 12 个月的数据 list2 一行的每个数据
		Map<String, List<List<String>>> fileContent4 = FileUtil.getFileContent4(filePath, monthOfDay);
		DecimalFormat df = new DecimalFormat("00");
		int row = 1;
		int spaceNum = 0;
		String rchName = "0";
		int day = 0;
		double daySBW = 1;
		while (true) {
			String fileContent5 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat", row);
			// 文件读取完毕
			if (StringUtils.isBlank(fileContent5)) {
				spaceNum++;
				if (spaceNum >= 21) {
					break;
				}

			}
			// 河流号
			if (row > 24) {
				if (fileContent5.contains("dasha")) {
					rchName = SzyjjkConstant.RCH35;
				} else if (fileContent5.contains("shenzhen")) {
					rchName = SzyjjkConstant.RCH43;
				} else if (fileContent5.contains("yuanlang")) {
					rchName = SzyjjkConstant.RCH49;
				} else if (fileContent5.contains("tianshuiwei")) {
					rchName = SzyjjkConstant.RCH59;
				}
			}
			// System.err.println("行数="+row+" 长度="+fileContent5.length()+"
			// 内容="+fileContent5);

			if (row == 1) {
				FileUtil.createFileOrWrite(hydroPath + "\\SBW_river_loads_test2.dat", fileContent5 + "\n");
			} else {
				// 判断没一行长度 获取日期
				if (fileContent5.length() >= 23) {
					year = fileContent5.substring(0, 4);
					String touTime = fileContent5.substring(0, 10);
					String touNum = fileContent5.substring(0, 23).trim();
					// 数据行 ||NumberUtils.isNumber(str)
					if (DateUtil.isDate(touTime) || NumberUtils.isNumber(touNum)) {
						// 日期转天
						// int getnewYeayDay1 = DateUtil.getnewYeayDay1(DateUtil.stringToDate(touTime));

						if (SzyjjkConstant.RCH35.equals(rchName) || SzyjjkConstant.RCH43.equals(rchName)) {
							List<List<String>> list = fileContent4.get(rchName);
							if (day > list.size() - 1) {
								day = 0;
							}

							// 一行到头" " 18 19 'NH4' 'NO3'
							// 12月
							if (daySBW > 12) {
								daySBW = 1;
							}
							// 保留12条 源文件中14条 超出的条数跳过
							if (daySBW == 12) {
								row = row + 2;
							}
							List<String> list2 = list.get(day);
							// 对应一月一号 17NO3_OUTkg 19 NH4_OUTkg
							String string2 = list2.get(17);
							String string3 = list2.get(19);

							String NO3 = string2.substring(0, 4) + "" + string2.substring(6, string2.length());
							String NH4 = string3.substring(0, 4) + "" + string3.substring(6, string3.length());
							String[] split = fileContent5.split("\t");
							String format = df.format(daySBW);
							split[0] = year + "/" + format + "/01" + "-00:00:00";
							daySBW++;
							// split[18] = "NH4";
							// split[19] = "NO3";
							split[18] = NH4;
							split[19] = NO3;
							StringBuilder sb = new StringBuilder();
							for (String string : split) {
								sb.append(string);
								sb.append("\t");
							}
							FileUtil.appendContent(hydroPath + "\\SBW_river_loads_test2.dat", sb.toString());
						} else if (SzyjjkConstant.RCH49.equals(rchName) || SzyjjkConstant.RCH59.equals(rchName)) {

							// 换行 如果头是日期
							if (DateUtil.isDate(touTime)) {
								if (daySBW > 12) {
									daySBW = 1;
								}

								List<List<String>> list = fileContent4.get(rchName);
								if (day > list.size() - 1) {
									day = 0;
								}

								List<String> list2 = list.get(day);
								// 对应一月一号 17NO3_OUTkg 19 NH4_OUTkg
								String NH4 = list2.get(17);
								String NO3 = list2.get(19);

								String[] split = fileContent5.split("  ");
								String format = df.format(daySBW);
								split[0] = year + "/" + format + "/01" + "-00:00:00";
								daySBW++;
								StringBuilder sb = new StringBuilder();
								// sb.append(fileContent5);

								for (String string : split) {
									sb.append(string);
									sb.append("\t");
								}
								sb.append("\n");
								String row1 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 1);
								String row2 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 2);
								String row3 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 3);
								StringBuilder sb1 = new StringBuilder();
								String[] split2 = row3.split("  ");

								split2[8] = NH4;
								split2[9] = NO3;
								for (String string : split2) {
									sb1.append(string);
									sb1.append("  ");
								}
								row3 = sb1.toString();
								// row3 行包括 No3 和 nh4
								String row4 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 4);
								String row5 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 5);
								String row6 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 6);
								String row7 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 7);
								String row8 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 8);
								String row9 = FileUtil.getFileContent5(spareFilePath + "SBW_river_loads_test2.dat",
										row + 9);

								sb.append(row1).append("\n").append(row2).append("\n").append(row3).append("\n")
										.append(row4).append("\n").append(row5).append("\n").append(row6).append("\n")
										.append(row7).append("\n").append(row8).append("\n").append(row9);
								FileUtil.appendContent(hydroPath + "\\SBW_river_loads_test2.dat", sb.toString());
								row = row + 9;

								if (daySBW - 1 == 12) {
									row = row + 20;
								}
							}
						} else {
							FileUtil.appendContent(hydroPath + "\\SBW_river_loads_test2.dat", fileContent5);
						}
					} else {
						// 非数据行 保持原样
						FileUtil.appendContent(hydroPath + "\\SBW_river_loads_test2.dat", fileContent5);
					}
				} else {
					// 非数据行 保持原样
					FileUtil.appendContent(hydroPath + "\\SBW_river_loads_test2.dat", fileContent5);
				}

			}
			row++;
		}

	}

	private void sBWWind(String siteId, RunModelInfo run) {

		logger.info("SBW_2015-wind.dat-------------------------" + new Date());
		List<RunSiteHKObs> findSiteData = runSiteService.findHkobsByDate(siteId, run);
		if (CollectionUtils.isEmpty(findSiteData)) {
			logger.info("风速站点的数据暂时无最近数据" + new Date());
		} else {
			String tou = "; windspeed model\nFUNCTIONS 'VWIND'\nBLOCK\nDATA\n";
			getContentSbw(findSiteData, tou);
		}

		logger.info("BW_2015-wind.bat文件输入完成-------------" + new Date());

	}

	private String getContentSbw(List<RunSiteHKObs> findSiteData, String tou) {
		String newFilePath = waterSBWResultPath + "SBW_2015-wind.dat";
		String oldFilePath = spareFilePath + "SBW_2015-wind.dat";

		// 获取要组装数据的行数
		StringBuilder sb = new StringBuilder();
		DecimalFormat df = new DecimalFormat("#0.0");

		// 获取当前最小的天
		int mixDay = DateUtil.getnewYeayDay1(findSiteData.get(0).getObsTime());
		int maxDay = DateUtil.getnewYeayDay1(findSiteData.get(findSiteData.size() - 1).getObsTime());

		for (RunSiteHKObs run : findSiteData) {
			Date obsTime = run.getObsTime();
			String dateToString1 = DateUtil.dateToString1(obsTime);
			dateToString1 = dateToString1 + "-00:00:00";
			sb.append(dateToString1);
			sb.append("	  ");
			// 风速
			double fss = Double.parseDouble(run.getObsFengsu()) * 1000 / 3600;
			String format = df.format(fss);
			// 转科学计数
			String scienceCount1 = scienceCount1(Double.parseDouble(format));
			sb.append(scienceCount1);
			sb.append("\n");
		}

		if (mixDay == 1) {
			// 数据库数据为第一天
			FileUtil.createFileOrWrite(newFilePath, tou + sb.toString());

			if (maxDay < 366) {
				int maxRow = maxDay + 4 + 1;
				// sb中不是一年的数据 需要补全旧数据 补全开始行数 maxRow
				StringBuilder sbb = new StringBuilder();
				while (true) {
					String fileContent5 = FileUtil.getFileContent5(oldFilePath, maxRow);
					if (StringUtils.isBlank(fileContent5)) {
						break;
					}
					maxRow++;
					sbb.append(fileContent5);
					sbb.append("\n");

				}
				FileUtil.appendContent(newFilePath, sbb.toString().substring(0, sbb.toString().length() - 1));
			}
		} else {
			// 数据库数据从中间开始
			StringBuilder sbb = new StringBuilder();
			int i = 1;
			while (true) {
				String fileContent5 = FileUtil.getFileContent5(oldFilePath, i);
				if (i == mixDay + 4) {
					break;
				}
				i++;
				sbb.append(fileContent5);
				sbb.append("\n");
			}
			FileUtil.createFileOrWrite(newFilePath, sbb.toString());
			FileUtil.appendContent(newFilePath, sb.toString().substring(0, sb.toString().length() - 1));
			if (maxDay < 366) {
				int maxRow = maxDay + 4 + 1;
				// sbwei中不是一年的数据 需要补全旧数据 补全开始行数 maxRow
				StringBuilder sbwei = new StringBuilder();
				while (true) {
					String fileContent5 = FileUtil.getFileContent5(oldFilePath, maxRow);
					if (StringUtils.isBlank(fileContent5)) {
						break;
					}
					maxRow++;
					sbwei.append(fileContent5);
					sbwei.append("\n");

				}
				FileUtil.appendContent(newFilePath, sbwei.toString().substring(0, sbwei.toString().length() - 1));
			}
		}

		String content = sb.toString();
		if (StringUtils.isBlank(tou)) {
			content = sb.toString().substring(0, sb.toString().length() - 1);
		}
		return content;
	}

	private void sBWRadsurf() {
		logger.info("SBW_2015-radsurf.dat取自Ocean model.tem最后一列的辐射，由于辐射数据暂时不能获取，该文件保持不变" + new Date());
	}

	/**
	 * 串联模型执行 无需加工参数文件的时候
	 */
	private void seriesConnectionModel(String fileRange, RunModelInfo run) {
		// System.out.println("手动执行的串联模型抽取方法");
		String userid = run.getUserId();
		String qianZhui = DateUtil.getDate();
		// 当上传文件后 用上传的文件 未上传文件 则用数据库数据

		List<String> siteList = SzyjjkConstant.SITELIST;
		List<String> siteList1 = SzyjjkConstant.SITELIST1;
		String dateType = SzyjjkConstant.DATETYPE;
		String dateType1 = SzyjjkConstant.DATETYPE1;
		String dateType2 = SzyjjkConstant.DATETYPE2;
		String dateType3 = SzyjjkConstant.DATETYPE3;
//			Date endDate = run.getEndDate();
//			if (null != run.getEndDate()) {
//				Date endDate1 = run.getEndDate();
//
//				if (endDate1.getTime() == DateUtil.getDateMin().getTime()) {
//					run.setEndDate(DateUtil.getNewDateRed1());
//				}
//			}
		/**
		 * 三种情况 1 有该文件并且未输出时间 在改文件上累加数据 2 有改文件并且输出时间 删除该文件 新增该文件以时间段为准 3 无该文件
		 */
		// 风速wnd
		inputWnd(siteList, dateType, run);
		// 降水psp
		inputPcp(siteList1, dateType1, run);
		// 相对湿度hmd
		inputHmd(siteList, dateType2, run);
		// 气温 tmp
		inputTmp(siteList1, dateType3, run);
		// exWater();
		/**
		 * 水动力 使用香港天文台数据 hka 香港国际机场 5V3PAOAB07091DN39WG9SC4KQ65NZN5K 统一删除该文件 然后新增
		 */

		// run.setEndDate(endDate);

		String siteId = SzyjjkConstant.JKOBS_HKA;
		bigWnd(siteId, run);
		oceanModel(siteId, run);
		szbDis();
		exNydro();
		FileUtil.copyFileComStart(waterNydroResultPath, hydroPath);
		// 该文件暂时不变 取自Ocean model.tem最后一列的辐射
		sBWRadsurf();
		// 台湾的风
		sBWWind(siteId, run);
		// output.rch 的1234 河 的 每月第一天 的氮磷 (目前只有氮磷)
		sBWRiverLoadsRest();
		String[] split = fileRange.split("_");
		getTest2Inp(split[0], split[1], "test2.inp");
		getTest2Inp(split[0], split[1], "test2_r.inp");

		exSBW();

		// 永久保存这个文件
		FileUtil.copyFile1(waterResultPath + "output.rch", permanentFilePath, qianZhui + "_");
		FileUtil.copyFile1(waterNydroResultPath + "trih-szb.dat", permanentFilePath, qianZhui + "_");
		FileUtil.copyFile1(waterNydroResultPath + "trim-szb.dat", permanentFilePath, qianZhui + "_");
		FileUtil.copyFile1(waterSBWResultPath + "test2_r.his", permanentFilePath, qianZhui + "_");
		// FileUtil.copyFile1(waterSBWResultPath + "test2_r.map", permanentFilePath,
		// qianZhui + "_");
		FileUtil.copyFile1(waterSBWResultPath + "test2_r-bal.his", permanentFilePath, qianZhui + "_");
		saveRunFilePath(qianZhui, "map", qianZhui + "_" + "test2_r.map", "sbw", userid, fileRange);
		saveRunFilePath(qianZhui, "rch", qianZhui + "_" + "output.rch", "water", userid, null);
		saveRunFilePath(qianZhui, "dat", qianZhui + "_" + "trih-szb.dat", "nydro", userid, null);
		saveRunFilePath(qianZhui, "dat", qianZhui + "_" + "trim-szb.dat", "nydro", userid, null);
		saveRunFilePath(qianZhui, "his", qianZhui + "_" + "test2_r.his", "sbw", userid, fileRange);
		saveRunFilePath(qianZhui, "bal.his", qianZhui + "_" + "test2_r-bal.his", "sbw", userid, null);
		if ("timing".equals(run.getType())) {
			runModelInfoService.updateById(run);
		}

	}

	public class RunTimeTask implements Runnable {
		private String fileRange;
		private String qianZ;
		private RunModelInfo run;

		public RunTimeTask(String fileRange, RunModelInfo run, String qianZ) {
			this.fileRange = fileRange;
			this.run = run;
			this.qianZ = qianZ;
		}

		@Override
		public void run() {
			//当 上个定时任务的 map数据没跑完的时候  这次的定时任务不执行
			if(TIMINGFLG==1) {
				if(StringUtils.isNoneBlank(modelMap.get("water"))) {
					logger.info("water模型执行中");
					return;
				}
				if(StringUtils.isNoneBlank(modelMap.get("nydro"))) {
					logger.info("nydro模型执行中");
					return;
				}
				if(StringUtils.isNoneBlank(modelMap.get("sbw"))) {
					logger.info("sbw模型执行中");
					return;
				}
				
				
				qianZ = DateUtil.getDate();
				logger.info("定时任务执行中-------" + new Date() + "-------map文件时间段：" + fileRange);
				isNoReadDataBase();
				// System.err.println("每一分钟输出执行一次" + fileRange);
				// 定时任务查询时间为 年初到当前时间的数据
				int year = DateUtil.getYear();
				String startDateA = year + "-01-01";
				run.setStartDate(DateUtil.stringToDate2(startDateA));
				run.setEndDate(new Date());

				run.setLastDate(new Date());
				// map 时间 明天0点-上个月今天0点
				//yyyy-MM-dd
				//String startDateC = DateUtil.getLastMonth();
				//过去23天
				String startDateC = DateUtil.getNewDateAddN(-23);
				//String endDateD = DateUtil.getNewDateAddN(-22);
				//预测7天
				String endDateD = DateUtil.getNewDateAddN(7);
				if(!endDateD.substring(0, 4).equals(startDateC.substring(0, 4))) {
					startDateC=endDateD.substring(0, 4)+"-01-01";
				}
				String type = run.getType();
				String userid = run.getUserId();
				water(run, type, qianZ, userid);
				nydro(run, type, qianZ, userid);
				swb(run, startDateC, endDateD, type, qianZ, userid, "1");
				
				// seriesConnectionModel(startDateC+"_"+endDateD, run);
			}
		}
	}

	/**
	 * 测试 定时任务
	 * 
	 * @param fileRange
	 * @param qianZ
	 * @param run
	 */
	private void 测试定时任务(String fileRange, String qianZ, RunModelInfo run) {
		run = new RunModelInfo();
		run.setType("timing");
		run.setUserId("admin");
		//qianZ = DateUtil.getDate();
		isNoReadDataBase();
		
		
		
		logger.info("定时任务执行中-------" + new Date() + "-------map文件时间段：" + fileRange);
		// System.err.println("每一分钟输出执行一次" + fileRange);
		// 定时任务查询时间为 年初到当前时间的数据
		int year = DateUtil.getYear();
		String startDateA = year + "-01-01";
		run.setStartDate(DateUtil.stringToDate2(startDateA));
		run.setEndDate(new Date());

		run.setLastDate(new Date());
		// map 时间 明天0点-上个月今天0点

		String startDateC = DateUtil.getLastMonth();
		String endDateD = DateUtil.getNewDateAddOne();
		
		if(!endDateD.substring(0, 4).equals(startDateC.substring(0, 4))) {
			startDateC=endDateD.substring(0, 4)+"-01-01";
		}
		String type = run.getType();
		String userid = run.getUserId();
		water(run, type, qianZ, userid);
		nydro(run, type, qianZ, userid);
		swb(run, startDateC, endDateD, type, qianZ, userid, "1");
	}

	private void savaSourceFile() {

		String a = waterNydroResultPath + "big.wnd";
		String filePathA = spareFilePath + "big.wnd";
		File fa = new File(filePathA);
		if (!fa.exists()) {
			FileUtil.copyFile2(a, spareFilePath);
		}

		String b = waterNydroResultPath + "Ocean model.tem";
		String filePathB = spareFilePath + "Ocean model.tem";
		File fb = new File(filePathB);
		if (!fb.exists()) {
			FileUtil.copyFile2(b, spareFilePath);
		}

		String c = waterResultPath + "output.rch";
		String filePathC = spareFilePath + "output.rch";
		File fc = new File(filePathC);
		if (!fc.exists()) {
			FileUtil.copyFile2(c, spareFilePath);
		}

		String d = waterNydroResultPath + "szb.dis";
		String filePathD = spareFilePath + "szb.dis";
		File fd = new File(filePathD);
		if (!fd.exists()) {
			FileUtil.copyFile2(d, spareFilePath);
		}

		String e = hydroPath + "SBW_river_loads_test2.dat";
		String filePathE = spareFilePath + "SBW_river_loads_test2.dat";
		File fe = new File(filePathE);
		if (!fe.exists()) {
			FileUtil.copyFile2(e, spareFilePath);
		}

		String f = waterSBWResultPath + "test2.inp";
		String filePathF = spareFilePath + "test2.inp";
		File ff = new File(filePathF);
		if (!ff.exists()) {
			FileUtil.copyFile2(f, spareFilePath);
		}
		String g = waterSBWResultPath + "test2_r.inp";
		String filePathG = spareFilePath + "test2_r.inp";
		File fg = new File(filePathG);
		if (!fg.exists()) {
			FileUtil.copyFile2(g, spareFilePath);
		}

	}

	private void szbDis() {
		// -map = key 1234 b=vale List<12月的>
		Map<String, List<String>> map = getOutputMap();
		if (map == null || map.isEmpty() || map.get(SzyjjkConstant.RCH35) == null
				|| map.get(SzyjjkConstant.RCH43) == null || map.get(SzyjjkConstant.RCH49) == null
				|| map.get(SzyjjkConstant.RCH59) == null) {
			return;
		}

		String newPath = spareFilePath + "szb.dis";
		String oldPath = waterNydroResultPath + "szb.dis";
		// 删除原 szb.dis
		// FileUtil.delFile(oldPath);
		// 生成新的szb.dis
		getRows(newPath, oldPath, 1, 12);
		getRows2(newPath, oldPath, 13, 26, map.get("35"));
		getRows1(newPath, oldPath, 27, 38);
		getRows2(newPath, oldPath, 39, 52, map.get("43"));
		getRows1(newPath, oldPath, 53, 64);
		getRows2(newPath, oldPath, 65, 78, map.get("49"));
		getRows1(newPath, oldPath, 79, 90);
		getRows2(newPath, oldPath, 91, 104, map.get("59"));
	}

	/**
	 * 获取 1-4河流的 360天平均到12个月份 的FLOW_OUTcms 数据
	 * 
	 * @return
	 */
	private Map<String, List<String>> getOutputMap() {
		List<Integer> actualMaximum = DateUtil.actualMaximum(2015);

		// 一条河的12个月份的平均值
		Map<String, List<String>> map = new HashMap<>();
		Map<String, List<String>> fileContent2 = FileUtil.getFileContent2(waterResultPath + "output.rch");
		for (Entry<String, List<String>> m : fileContent2.entrySet()) {
			// System.err.println(m.getKey()+"----------------------");
			List<String> value = m.getValue();
			double sum = 0;
			// 月
			int z = 0;
			// 多少条数据计算
			int i = 0;
			for (String string : value) {
				i++;
				sum += Double.parseDouble(string);
				// System.out.println(string);
				if (i == actualMaximum.get(z)) {
					double avg = sum / actualMaximum.get(z);
					// System.err.println("--------------------------"+(z+1)+"月");
					List<String> list = map.get(m.getKey());
					if (CollectionUtils.isEmpty(list)) {
						List<String> mapList = new ArrayList<String>();
						mapList.add(avg + "");
						map.put(m.getKey(), mapList);
					} else {
						list.add(avg + "");
						map.put(m.getKey(), list);
					}
					i = 0;
					sum = 0;
					z++;
					if (z == 12) {
						break;
					}
				}
			}
		}
		return map;
	}

	/**
	 * 相对湿度，空气温度，云覆盖度，辐射强度
	 * 
	 * @param siteId
	 * @param run
	 */
	private void oceanModel(String siteId, RunModelInfo run) {
		// 相对湿度，空气温度，云覆盖度，辐射强度
		logger.info("Ocean model.tem-------------------------" + new Date());
		boolean biaoji = false;
		// 新文件
		// String newFilePath = waterNydroResultPath + "Ocean model.tem";

		// 每次都新生成
		// FileUtil.delFile(newFilePath);
		if (null != run.getStartDate() && null != run.getEndDate()) {
			biaoji = true;
		}

		// 1.空文件 2.空文件读取所有数据

		List<RunSiteHKObs> findSiteData = null;
		if (biaoji) {
			findSiteData = runSiteService.findHkobsByDate(siteId, run);
		} else {
			findSiteData = runSiteService.findHkobs(siteId);
		}
		if (CollectionUtils.isEmpty(findSiteData)) {
			logger.info("Ocean model数据暂时无最近数据" + run.getStartDate() + "-" + run.getEndDate());
		} else {
			getContentNydro(findSiteData, "Ocean");
			// 测试文件
			// FileUtil.createFileOrWrite(newFilePath, content);
		}

		logger.info("Ocean model.tem文件输入完成-------------" + new Date());

	}

	/**
	 * 组装big.wnd文件
	 * 
	 * @param siteId
	 * @param run
	 */
	private void bigWnd(String siteId, RunModelInfo run) {

		logger.info("big.wnd-------------------------" + new Date());
		boolean biaoji = false;
		// 新文件
		// String newFilePath = waterNydroResultPath + "big.wnd";

		// 每次都新生成
		// FileUtil.delFile(newFilePath);
		if (null != run.getStartDate() && null != run.getEndDate()) {
			biaoji = true;
		}

		// 1.空文件 2.空文件读取所有数据

		List<RunSiteHKObs> findSiteData = null;
		if (biaoji) {
			findSiteData = runSiteService.findHkobsByDate(siteId, run);
		} else {
			findSiteData = runSiteService.findHkobs(siteId);
		}
		if (CollectionUtils.isEmpty(findSiteData)) {
			logger.info("风速站点的数据暂时无数据,范围" + run.getStartDate() + "-" + run.getEndDate());
		} else {
			getContentNydro(findSiteData, "wnd");
			// System.err.println(content);
			// 测试文件
			// FileUtil.createFileOrWrite(newFilePath, content);
		}

		logger.info("big.wnd文件输入完成-------------" + new Date());

	}

	private String getContentNydro(List<RunSiteHKObs> findSiteData, String type) {
		List<String> bigWnd = new ArrayList<>();
		List<String> ocean = new ArrayList<>();
		List<String> radiation = new ArrayList<>();
		String filePathNew = null;
		String newFilePath = null;
		if ("wnd".equals(type)) {
			newFilePath = waterNydroResultPath + "big.wnd";
			// 旧文件
			filePathNew = spareFilePath + "big.wnd";
			bigWnd = FileUtil.getFileContent1(filePathNew, "	", 1, 1);
			if (CollectionUtils.isEmpty(bigWnd)) {
				return "";
			}
		} else if ("Ocean".equals(type)) {
			newFilePath = waterNydroResultPath + "Ocean model.tem";
			// 旧文件
			filePathNew = spareFilePath + "Ocean model.tem";
			ocean = FileUtil.getFileContent1(filePathNew, "	", 1, 1);
			radiation = FileUtil.getFileContent1(filePathNew, "	", 5, 1);
			if (CollectionUtils.isEmpty(ocean) || CollectionUtils.isEmpty(radiation)) {
				return "";
			}
		}

		StringBuilder sb = new StringBuilder();

		DecimalFormat df = new DecimalFormat("#0.00");
		// 获取当前最小的天
		int mixDay = DateUtil.getnewYeayDay1(findSiteData.get(0).getObsTime());
		int maxDay = DateUtil.getnewYeayDay1(findSiteData.get(findSiteData.size() - 1).getObsTime());

		int num = 0;

		for (RunSiteHKObs runSiteHKObs : findSiteData) {
			if ("wnd".equals(type)) {
				// 该时间转化天数对应老文件中的行
				Date obsTime = runSiteHKObs.getObsTime();

				int day = DateUtil.getnewYeayDay1(obsTime);
				// com1 文件中1行 对应第一天
				String com1 = bigWnd.get(day - 1);
				sb.append(com1);
				sb.append("	");
				// 风速 m/s
				String obsFengsu = runSiteHKObs.getObsFengsu();
				String obsFengxiang = runSiteHKObs.getObsFengxiang();

				obsFengsu = checkResStr(obsFengsu);
				obsFengxiang = checkResStr(obsFengxiang);
				double fsH = Double.parseDouble(obsFengsu);
				// 转m/s
				double fss = fsH * 1000 / 3600;
				String format = df.format(fss);
				// 转科学计数风速
				String res1 = scienceCount1(Double.parseDouble(format));
				// 转科学计数风向
				String res2 = scienceCount1(Double.parseDouble(format));
				sb.append(res1);
				sb.append("	");
				sb.append(res2);
			} else if ("Ocean".equals(type)) {

				// 相对湿度，空气温度，云覆盖度
				Date obsTime = runSiteHKObs.getObsTime();

				int day = DateUtil.getnewYeayDay1(obsTime);
				/**
				 * 因为 Ocean 文件的第一列不能出现重复的 所以 查询时间最小值 判断 当最小值出现2回时 即 20190101=1 20200101 =1 的时候
				 * 选取都是选取第一行第一列的 数据 此时 第一行第一列的数据出现重复 文件执行时回报错
				 */
				if (mixDay == day) {
					num++;
				}
				if (num == 2) {
					break;
				}
				String com1 = ocean.get(day - 1);
				sb.append(com1);
				sb.append("	");
				// 相对湿度
				String obsShidu = runSiteHKObs.getObsShidu();
				// 平均温度
				String obsQiwenPj = runSiteHKObs.getObsQiwenPj();
				// 平均云量
				String obsYunliang = runSiteHKObs.getObsYunliang();
				obsShidu = checkResStr(obsShidu);
				obsQiwenPj = checkResStr(obsQiwenPj);
				obsYunliang = checkResStr(obsYunliang);

				// 湿度
				String res1 = scienceCount1(Double.parseDouble(obsShidu));
				// 温度 5个0
				String format = df.format(Double.parseDouble(obsQiwenPj) / 10);
				String res2 = format + "00000E+01";
				// 云量
				String res3 = scienceCount1(Double.parseDouble(obsYunliang));
				sb.append(res1);
				sb.append("	");
				sb.append(res2);
				sb.append("	");
				sb.append(res3);
				sb.append("	");
				String com2 = radiation.get(day - 1);
				sb.append(com2);

			}
			sb.append("\n");
		}

		if (mixDay == 1) {
			// 数据库数据为第一天
			FileUtil.createFileOrWrite(newFilePath, sb.toString());

			if (maxDay < 366) {
				int maxRow = maxDay + 1;
				// sb中不是一年的数据 需要补全旧数据 补全开始行数 maxRow
				StringBuilder sbb = new StringBuilder();
				while (true) {
					String fileContent5 = FileUtil.getFileContent5(filePathNew, maxRow);
					if (StringUtils.isBlank(fileContent5)) {
						break;
					}
					maxRow++;
					sbb.append(fileContent5);
					sbb.append("\n");

				}
				FileUtil.appendContent(newFilePath, sbb.toString().substring(0, sbb.toString().length() - 1));
			}
		} else {
			// 数据库数据从中间开始
			StringBuilder sbb = new StringBuilder();
			int i = 1;
			while (true) {
				String fileContent5 = FileUtil.getFileContent5(filePathNew, i);
				if (i == mixDay) {
					break;
				}
				i++;
				sbb.append(fileContent5);
				sbb.append("\n");
			}
			FileUtil.createFileOrWrite(newFilePath, sbb.toString());
			// FileUtil.appendContent(newFilePath, sb.toString().substring(0,
			// sb.toString().length()-1));
			if (maxDay < 366) {
				int maxRow = maxDay + 1;
				// sbwei中不是一年的数据 需要补全旧数据 补全开始行数 maxRow
//				StringBuilder sbwei = new StringBuilder();
				while (true) {
					String fileContent5 = FileUtil.getFileContent5(filePathNew, maxRow);
					if (StringUtils.isBlank(fileContent5)) {
						break;
					}
					maxRow++;
					// sbwei.append(fileContent5);
					// sbwei.append("\n");
					sb.append(fileContent5);
					sb.append("\n");

				}
				FileUtil.appendContent(newFilePath, sb.toString().substring(0, sb.toString().length() - 1));
			}
		}
		return null;// sb.toString();

	}

	private String checkResStr(String data) {
		if (StringUtils.isBlank(data)) {
			data = "0";
			return data;
		}
		if (data.contains("#")) {
			data = data.replaceAll("#", "");
			return data;
		}
		if ("***".equals(data)) {
			data = "0";
			return data;
		}
		return data;

	}

	/**
	 * 风速
	 * 
	 * @param parseDouble
	 * @return
	 */
	private String scienceCount1(double parseDouble) {
		DecimalFormat df = new DecimalFormat("#0.00");
		String res = "0.0000000E+00";
		if (parseDouble >= 1 && parseDouble < 10) {
			String format = df.format(parseDouble);
			res = format + "00000E+00";
		} else if (parseDouble >= 10 && parseDouble < 100) {
			String format = df.format(parseDouble / 10);
			res = format + "00000E+01";
		} else if (parseDouble >= 100 && parseDouble < 1000) {
			String format = df.format(parseDouble / 100);
			res = format + "00000E+02";
		} else if (parseDouble >= 0.1 && parseDouble < 1) {
			String format = df.format(parseDouble * 10);
			res = format + "00000E-01";
		}
		return res;
	}

	/**
	 * 模型列表
	 * 
	 * @param type
	 * @param operation
	 * @return
	 */
	@RequestMapping("/modelList.do")
	@ResponseBody
	public ResponseDataBo<RunModelInfo> modelList() {
		ResponseDataBo<RunModelInfo> rd = new ResponseDataBo<RunModelInfo>();

		List<RunModelInfo> findList = runModelInfoService.findListbystate(0);
		rd.setList(findList);
		return rd;
	}

	/**
	 * 模型输入输出文件详细
	 * 
	 * @param type
	 * @param operation
	 * @return
	 */
	@RequestMapping("/detailed.do")
	@ResponseBody
	public ResponseDataBo<ModelInputAndOotput> modelPut(String type, String operation) {
		ResponseDataBo<ModelInputAndOotput> rd = new ResponseDataBo<ModelInputAndOotput>();
		if (StringUtils.isBlank(operation) || StringUtils.isBlank(operation)) {
			rd.setCode(0);
			rd.setMessage("请输入参数");
			return rd;
		}

		List<ModelInputAndOotput> list = new ArrayList<>();

		if ("water".equals(type)) {
			// 流域
			if ("in".equals(operation)) {
				for (String key : SzyjjkConstant.WATER_INPUT.keySet()) {
					String value = SzyjjkConstant.WATER_INPUT.get(key);
					if ("0".equals(value)) {
						ModelInputAndOotput mo = new ModelInputAndOotput();
						mo.setType(type);
						mo.setModelName("水流域模型");
						mo.setInputFileName(key);
						list.add(mo);
					}
				}
			} else {
				for (String fileName : SzyjjkConstant.WATER_OUTPUT) {
					ModelInputAndOotput mo = new ModelInputAndOotput();
					mo.setType(type);
					mo.setModelName("水流域模型");
					mo.setInputFileName(fileName);
					list.add(mo);
				}
			}
		} else if ("nydro".equals(type)) {
			// 水动力
			if ("in".equals(operation)) {
				for (String key : SzyjjkConstant.NYDRO_INPUT.keySet()) {
					String value = SzyjjkConstant.NYDRO_INPUT.get(key);
					if ("0".equals(value)) {
						ModelInputAndOotput mo = new ModelInputAndOotput();
						mo.setType(type);
						mo.setModelName("水动力模型");
						mo.setInputFileName(key);
						list.add(mo);
					}
				}
			} else {
				for (String fileName : SzyjjkConstant.NYDRO_OUTPUT) {
					ModelInputAndOotput mo = new ModelInputAndOotput();
					mo.setType(type);
					mo.setModelName("水动力模型");
					mo.setInputFileName(fileName);
					list.add(mo);
				}
			}
		} else if ("sbw".equals(type)) {
			// 水质
			if ("in".equals(operation)) {
				for (String key : SzyjjkConstant.SBW_INPUT.keySet()) {
					String value = SzyjjkConstant.SBW_INPUT.get(key);
					if ("0".equals(value)) {
						ModelInputAndOotput mo = new ModelInputAndOotput();
						mo.setType(type);
						mo.setModelName("水质模型");
						mo.setInputFileName(key);
						list.add(mo);
					}
				}
			} else {
				for (String fileName : SzyjjkConstant.SBW_OUTPUT) {
					ModelInputAndOotput mo = new ModelInputAndOotput();
					mo.setType(type);
					mo.setModelName("水质模型");
					mo.setInputFileName(fileName);
					list.add(mo);
				}
			}
		}

		rd.setList(list);
		return rd;
	}

	/**
	 * 下载
	 */
	@RequestMapping("/fileDown.do")
	@ResponseBody
	public void down(String type, String fileName, HttpServletResponse response) {
		response.setStatus(501);
		String fileDownLoadPath = "";
		if ("water".equals(type)) {
			fileDownLoadPath = waterResultPath;
		} else if ("nydro".equals(type)) {
			fileDownLoadPath = waterNydroResultPath;
		} else if ("sbw".equals(type)) {
			fileDownLoadPath = waterSBWResultPath;
			if (fileName.equals("SBW_river_loads_test2.dat")) {
				fileDownLoadPath = hydroPath;
			}
		}
		try {
			fileDownLoadPath = fileDownLoadPath + fileName;
			// 读到流中
			InputStream inStream = new FileInputStream(fileDownLoadPath);// 文件的存放路径
			// 设置输出的格式
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.setStatus(200);
			// 循环取出流中的数据
			byte[] b = new byte[1024];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传
	 */
	@RequestMapping("/upload.do")
	@ResponseBody
	public ResponseBo upload(HttpServletRequest request) {
		ResponseBo rb = new ResponseBo();
		MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
		MultipartFile multipartFile = params.getFile("fileUpload");
		if (!multipartFile.isEmpty()) {
			String fileDownLoadPath = "";
			String fileName = multipartFile.getOriginalFilename();
			int chenk = checkFileName(fileName);
			if (0 == checkFileName(fileName)) {
				rb.setCode(0);
				rb.setMessage("非模型需要的文件");
				return rb;
			}
			long size = multipartFile.getSize();
			long max = 10L * 1024l * 1024l;
			if (size > max) {
				rb.setCode(0);
				rb.setMessage("上传文件大小超过10M");
				return rb;
			}
			if (chenk == 1 || chenk == 2) {
				fileDownLoadPath = waterResultPath;
				/**
				 * 排除掉配置文件
				 */
				if (fileName.equals("hmd.hmd") || fileName.equals("pcp1.pcp") || fileName.equals("Tmp1.Tmp")
						|| fileName.equals("wnd.wnd")) {
					// modelMap.put("water", fileName);
				}

			} else if (chenk == 3 || chenk == 4) {
				fileDownLoadPath = waterNydroResultPath;
				if (fileName.equals("big.wnd") || fileName.equals("Ocean model.tem") || fileName.equals("szb.dis")) {
					// modelMap.put("nydro", fileName);
				}

			} else {
				fileDownLoadPath = waterSBWResultPath;
				if (fileName.equals("SBW_2015-radsurf.dat") || fileName.equals("SBW_2015-wind.dat")
						|| fileName.equals("SBW_river_loads_test2.dat")) {
					// modelMap.put("sbw", fileName);
				}

				if ("SBW_river_loads_test2.dat".equals(fileName)) {
					// 改水质文件不再水质模型跟目录下
					fileDownLoadPath = hydroPath;
				}

			}
			//modelMap.put(fileName, "1");
			System.out.println("上传文件位置" + fileDownLoadPath);
			/**
			 * 如果上传的文件名包括之前的固定取值文件 则删除固定取值文件 重新复制该文件到固定取值文件位置
			 */
			isNotCopy(fileName);
			try {
				FileUtil.fileUpload(multipartFile, fileDownLoadPath);

				// 永久保存的文件
				saveFileNewPath(fileName);
			} catch (Exception e) {
				e.printStackTrace();
				rb.setCode(0);
				rb.setMessage("上传文件失败");
				return rb;
			}
		} else {
			rb.setCode(0);
			rb.setMessage("上传文件空");
			return rb;
		}
		return rb;
	}

	@RequestMapping("uploadfile.do")
	@ResponseBody
	public ResponseBo uploadfile(HttpServletRequest request){
		ResponseBo rb = new ResponseBo();
		MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
		MultipartFile multipartFile = params.getFile("fileUpload");
		String res = "";
		if (!multipartFile.isEmpty()) {
			String fileDownLoadPath = uploadpath;
			String fileName = multipartFile.getOriginalFilename();
			long size = multipartFile.getSize();
			long max = 10L * 1024l * 1024l;
			if (size > max) {
				rb.setCode(0);
				rb.setMessage("上传文件大小超过10M");
				return rb;
			}
			System.out.println("上传文件位置" + fileDownLoadPath);

			try {
				String finalpath = FileUtil.fileUpload(multipartFile, fileDownLoadPath);
				rb.setPath(multipartFile.getOriginalFilename());

				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				ArrayList<SysHardWareData> insertlist = new ArrayList<>();
				//同步到数据库
				if (!fileName.contains("xlsx")){
					HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(finalpath));
					HSSFSheet sheet = workbook.getSheetAt(0);
					for (int i = 0; i < sheet.getLastRowNum(); i++) {
						if (i > 2) {
							Row row = sheet.getRow(i);
							Cell cell = row.getCell(0);
							Date date = sf.parse(cell.getStringCellValue());
							//除时间项
							for (int j = 1; j < row.getLastCellNum(); j++) {

								row.getCell(j).setCellType(CellType.STRING);
								SysHardWareData sysHardWareData = new SysHardWareData();
								sysHardWareData.setDataTime(date);
								sysHardWareData.setDataNameCh(sheet.getRow(1).getCell(j).getStringCellValue());
								sysHardWareData.setDataValue(row.getCell(j).getStringCellValue());
								sysHardWareData.setDataFileName(multipartFile.getOriginalFilename());
								sysHardWareData.setId(UUIDUtils.getUUID());
//								sysHearWordService.saveSysHardWareDate(sysHardWareData);
								insertlist.add(sysHardWareData);
							}
						}

					}
				}else {
					XSSFWorkbook workbook = new XSSFWorkbook(finalpath);
					XSSFSheet sheet = workbook.getSheetAt(0);
					for (int i = 0; i < sheet.getLastRowNum(); i++) {
						if (i > 2) {
							Row row = sheet.getRow(i);
							Cell cell = row.getCell(0);
							Date date = sf.parse(cell.getStringCellValue());
							//除时间项
							for (int j = 1; j < row.getLastCellNum(); j++) {
								SysHardWareData sysHardWareData = new SysHardWareData();
								sysHardWareData.setDataTime(date);
								sysHardWareData.setDataNameCh(sheet.getRow(1).getCell(j).getStringCellValue());
								sysHardWareData.setDataValue(row.getCell(j).getStringCellValue());
								sysHardWareData.setDataFileName(multipartFile.getOriginalFilename());
								sysHardWareData.setId(UUIDUtils.getUUID());
//								sysHearWordService.saveSysHardWareDate(sysHardWareData);
								insertlist.add(sysHardWareData);
							}
						}

					}
				}
				res = JSONObject.toJSONString(insertlist);
			} catch (Exception e) {
				e.printStackTrace();
				rb.setCode(0);
				rb.setMessage("上传文件失败");
				return rb;
			}
		} else {
			rb.setCode(0);
			rb.setMessage("上传失败");
			return rb;
		}
		rb.setCode(1);
		rb.setMessage(res);
		return rb;

	}

	private void isNotCopy(String fileName) {

		if (fileName.equals("big.wnd") || fileName.equals("Ocean model.tem") || fileName.equals("output.rch")
				|| fileName.equals("szb.dis") || fileName.equals("SBW_river_loads_test2.dat")) {

			File fa = new File(spareFilePath + fileName);
			if (!fa.exists()) {
				fa.delete();
			}

		}

	}

	private void saveFileNewPath(String fileName) {
		if ("output.rch".equals(fileName)) {
			// 永久保存这个文件 output.rch
			FileUtil.copyFile1(waterResultPath + fileName, permanentFilePath, "");
		} else if (fileName.startsWith("trih") && fileName.endsWith(".dat")) {
			FileUtil.copyFile1(waterNydroResultPath + fileName, permanentFilePath, "");
		} else if (fileName.startsWith("trim") && fileName.endsWith(".dat")) {
			FileUtil.copyFile1(waterNydroResultPath + fileName, permanentFilePath, "");
		} else if ("test2_r.his".equals(fileName) || "test2_r.map".equals(fileName)
				|| "test2_r-bal.his".equals(fileName)) {
			FileUtil.copyFile1(waterSBWResultPath + fileName, permanentFilePath, "");
		}
	}

	private void inputTmp(List<String> list, String dateType, RunModelInfo run) {

		logger.info("tmp-------------------------" + new Date());
		String type = "tmp";
		String tou = "Station  tmp_004,tmp_001,tmp_003,tmp_005,tmp_002,tmp_007,tmp_006,tmp_008,\nLati         22.5      22.6      22.6      22.5      22.5      22.5      22.5      22.4\nLong        114.1     114.0     114.0     114.0     114.0     114.1     114.0     114.1\nElev           19        87        12        63        55        10        31        16\n";
		// 查询文件并获取文件水流域风速文件最后一行
		String filePath = waterResultPath + "Tmp1.Tmp";

		Map<String, List<RunSiteData>> map = new HashMap<>();

		// 1.空文件 2.空文件读取所有数据
		for (String site : list) {

			List<RunSiteData> findSiteData = runSiteService.findSiteDataOrderByDate(site, dateType, run);

			if (CollectionUtils.isNotEmpty(findSiteData)) {
				map.put(site, findSiteData);
			}
		}
		if (map.isEmpty()) {
			logger.info("降水站点的数据暂时无最近数据" + new Date());
		} else {
			// String content = getContent(tou, map, list, type);
			FileUtil.createFileOrWrite(filePath, tou);
			String n = "Tmp1.Tmp";
			getContentWa(filePath, map, list, type, n);
		}

		logger.info(type + "文件输入完成-------------" + new Date());

	}

	private void inputHmd(List<String> list, String dateType, RunModelInfo run) {

		logger.info("hmd-------------------------" + new Date());
		String type = "hmd";
		String tou = "Input File hmd.hmd          " + DateUtil.getToDate() + " ArcSWAT 2012.10_2.17\n";
		// 查询文件并获取文件水流域风速文件最后一行
		String filePath = waterResultPath + "hmd.hmd";

		Map<String, List<RunSiteData>> map = new HashMap<>();

		// 1.空文件 2.空文件读取所有数据
		for (String site : list) {
			List<RunSiteData> findSiteData = runSiteService.findSiteDataOrderByDate(site, dateType, run);

			if (CollectionUtils.isNotEmpty(findSiteData)) {
				map.put(site, findSiteData);
			}
		}
		if (map.isEmpty()) {
			logger.info("降水站点的数据暂时无最近数据" + new Date());
		} else {
			FileUtil.createFileOrWrite(filePath, tou);
			String n = "hmd.hmd";
			getContentWa(filePath, map, list, type, n);
		}

		logger.info(type + "文件输入完成-------------" + new Date());

	}

	private void inputPcp(List<String> list, String dateType, RunModelInfo run) {
		logger.info("pcp-------------------------" + new Date());
		String type = "pcp";
		String tou = "Station  pcp_004,pcp_001,pcp_003,pcp_005,pcp_002,pcp_007,pcp_006,pcp_008,\nLati    22.5 22.6 22.6 22.5 22.5 22.5 22.5 22.4\nLong   114.1114.0114.0114.0114.0114.1114.0114.1\nElev      19   87   12   63   55   10   31   16\n";
		// 查询文件并获取文件水流域风速文件最后一行
		String filePath = waterResultPath + "pcp1.pcp";

		Map<String, List<RunSiteData>> map = new HashMap<>();

		// 1.空文件 2.空文件读取所有数据
		for (String site : list) {

			List<RunSiteData> findSiteData = runSiteService.findSiteDataOrderByDate(site, dateType, run);

			if (CollectionUtils.isNotEmpty(findSiteData)) {
				map.put(site, findSiteData);
			}
		}
		if (map.isEmpty()) {
			logger.info("降水站点的数据暂时无最近数据" + new Date());
		} else {

			// System.err.println(content);
			FileUtil.createFileOrWrite(filePath, tou);
			String n = "pcp1.pcp";
			getContentWa(filePath, map, list, type, n);

		}
		logger.info(type + "文件输入完成-------------" + new Date());
	}

	/**
	 * 封装风速数据
	 */
	private void inputWnd(List<String> list, String dateType, RunModelInfo run) {
		logger.info("wnd-------------------------" + new Date());
		// 前台输入时间 按时间查询 不输入 时间 查询全部
		String type = "wnd";
		String wnd1 = "Input File wnd.wnd          " + DateUtil.getToDate() + " ArcSWAT 2012.10_2.17\n";
		// 查询文件并获取文件水流域风速文件最后一行
		String filePath = waterResultPath + "wnd.wnd";
		Map<String, List<RunSiteData>> map = new HashMap<>();

		for (String site : list) {
			List<RunSiteData> findSiteData = runSiteService.findSiteDataOrderByDate(site, dateType, run);
			;
			if (CollectionUtils.isNotEmpty(findSiteData)) {
				// 对应站点对应数据
				map.put(site, findSiteData);
			} else {
				// 当有一个站点的数据是空的时候这个 不处理当前文件
				logger.info("该站点无风速数据 该文件不更新id=" + site + "--" + new Date());
				return;
			}
		}
		if (map.isEmpty()) {
			logger.info("风速站点的数据暂时无最近数据" + new Date());
		} else {

			// 创建初始文件增加头 后续在该文件上最佳
			FileUtil.createFileOrWrite(filePath, wnd1);
			String n = "wnd.wnd";
			getContentWa(filePath, map, list, type, n);
		}
		logger.info(type + "文件输入完成-------------" + new Date());
	}

	private void getContentWa(String path, Map<String, List<RunSiteData>> map, List<String> list, String type,
			String n) {
		// path waterResultPath + "wnd.wnd";
		// 获取要组装数据的行数 读一行 写一行
		/**
		 * 这个是把2015年数据替换成2020的
		 */
		// 旧的文件
		int row = 2923;
		if ("pcp1.pcp".equals(n) || "Tmp1.Tmp".equals(n)) {
			row = 2926;
		}

//		
//		for(int i=1; i<row;i++) {
//			String fileContent5="";
//			if("pcp1.pcp".equals(n)||"Tmp1.Tmp".equals(n)) {
//				 fileContent5 = FileUtil.getFileContent5(spareFilePath+ n, i+1+3);
//			}else {
//			
//				fileContent5 = FileUtil.getFileContent5(spareFilePath+ n, i+1);
//			}
//			FileUtil.appendContent(path, fileContent5);
//		}
		/**
		 * 这个是在2015年数据上累加的
		 */
		int od = 0;
		if (type.equals("wnd")) {
			od = 2;
		} else if (type.equals("pcp")) {
			od = 5;
		} else if (type.equals("hmd")) {
			od = 2;
		} else if (type.equals("tmp")) {
			od = 5;
		}
		while (true) {
			String fileContent5 = FileUtil.getFileContent5(spareFilePath + n, od);
			od++;
			if (StringUtils.isBlank(fileContent5)) {
				break;
			}
			FileUtil.appendContent(path, fileContent5);

		}
//-----------------------------------------------------

		boolean b = true;
		// 基准标记
		List<RunSiteData> jizhun = map.get(list.get(0));
		String aaa = DateUtil.dateToString(jizhun.get(0).getDataTime());
		String[] frist = aaa.split("-");

		int j = 0;
		// 源文件行数
		int i = 0;
		while (true) {
			if (i == 365) {
				break;
			}
			StringBuilder sb = new StringBuilder();
			// 8站点
			for (int z = 0; z < list.size(); z++) {

				List<RunSiteData> dataRow = map.get(list.get(z));
				if (j == jizhun.size()) {
					b = true;
					break;
				}
				RunSiteData runSiteData = jizhun.get(j);

				Date dataTime = runSiteData.getDataTime();
				int getnewYeayDay = DateUtil.getnewYeayDay1(dataTime);

				// 如果该天有数据 使用 否装使用旧的
				if (getnewYeayDay - 1 == i) {
					RunSiteData runSiteData1 = dataRow.get(j);
					String avg = "";
					if (type.equals("wnd")) {
						// 获取平均数据 xxxx.xxx
						avg = getAvgWnd(runSiteData1);

					} else if (type.equals("pcp")) {
						// xxx.x
						avg = getAvgPcp(runSiteData1);

					} else if (type.equals("hmd")) {
						// xxxx.xxx
						avg = getAvgHmd(runSiteData1);

					} else if (type.equals("tmp")) {
						// xxx.x
						avg = getAvgTmp(runSiteData1);
					}

					if (z == 0) {
						String ddd = DateUtil.dateToString(dataTime);
						String[] split = ddd.split("-");
						sb.append(split[0] + getnewYeayDay);
					}
					if (z == list.size() - 1) {
						j++;
						b = false;
					}

					sb.append(avg);
				} else {
					b = true;
					break;
				}
			}
			if (b) {
				String fileContent5 = FileUtil.getFileContent5(spareFilePath + n, row + i + 1);
				sb = new StringBuilder(fileContent5.replaceAll("2015", frist[0]));
			}
			FileUtil.appendContent(path, sb.toString());
			sb = new StringBuilder();
			i++;
		}

	}

	/**
	 * 组装数据库数据 返回要输入文件数据
	 * 
	 * @param wnd1
	 * @param findSiteData
	 * @param type         降雨pcp1.pcp、温度Tmp1.Tmp、风速wnd.wnd、相对湿度hmd.hmd
	 * @return
	 */
	private String getContent(String tou, Map<String, List<RunSiteData>> map, List<String> list, String type) {
		List<RunSiteData> dataRow = map.get(list.get(0));
		// 获取要组装数据的行数
		StringBuilder sb = new StringBuilder(tou);
		for (int i = 0; i < dataRow.size(); i++) {
			// 组装行数据
			for (int j = 0; j < list.size(); j++) {
				// 获取这个id的集合
				List<RunSiteData> dataRow1 = map.get(list.get(j));
				// 第 i个实体
				RunSiteData runSiteData = dataRow1.get(i);

				if (j == 0) {
					Date dataTime = runSiteData.getDataTime();
					String getnewYeayDay = DateUtil.getnewYeayDay(dataTime);
					sb.append(getnewYeayDay);
				}
				if (type.equals("wnd")) {
					// 获取平均数据 xxxx.xxx
					String avg = getAvgWnd(runSiteData);
					sb.append(avg);
				} else if (type.equals("pcp")) {
					// xxx.x
					String avg = getAvgPcp(runSiteData);
					sb.append(avg);
				} else if (type.equals("hmd")) {
					// xxxx.xxx
					String avg = getAvgHmd(runSiteData);
					sb.append(avg);

				} else if (type.equals("tmp")) {
					// xxx.x
					String avg = getAvgTmp(runSiteData);
					sb.append(avg);
				}
			}
			sb.append("\n");
		}
		String content = sb.toString();
		if (StringUtils.isBlank(tou)) {
			content = sb.toString().substring(0, sb.toString().length() - 1);
		}
		return content;
	}

	/**
	 * 温度最大最小
	 * 
	 * @param runSiteData
	 * @return
	 */
	private String getAvgTmp(RunSiteData runSiteData) {
		Map<String, Object> map = new HashMap<String, Object>();
		Class<?> clazz = runSiteData.getClass();
		for (Field field : clazz.getDeclaredFields()) {
			field.setAccessible(true);
			String fieldName = field.getName();
			Object object = null;
			try {
				object = field.get(runSiteData);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				logger.info(e.getMessage());
			}
			map.put(fieldName, object);
		}

		double max = -100.0d;
		double mix = 100.0d;
		for (String key : map.keySet()) {
			if (key.contains("dataH")) {
				Object object = map.get(key);
				String value = null;
				if (object == null) {
					value = "0.0";
				} else {
					value = object.toString();
				}

				double valueDouble = Double.parseDouble(value);
				if (valueDouble > max) {
					max = valueDouble;
				}
				if (mix > valueDouble) {
					mix = valueDouble;
				}
			}
		}

		DecimalFormat df1 = new DecimalFormat("000.0");
		DecimalFormat df2 = new DecimalFormat("000.0");
		String format1;
		String format2;
		if (max > 0) {
			format1 = df1.format(max);
		} else {
			format1 = df2.format(max);
		}
		if (mix > 0) {
			format2 = df1.format(mix);
		} else {
			format2 = df2.format(mix);
		}

		return format1 + format2;
	}

	private String getAvgHmd(RunSiteData runSiteData) {
		double hour = 24;
		String dH0 = runSiteData.getDataH0();
		String dH1 = runSiteData.getDataH1();
		String dH2 = runSiteData.getDataH2();
		String dH3 = runSiteData.getDataH3();
		String dH4 = runSiteData.getDataH4();
		String dH5 = runSiteData.getDataH5();
		String dH6 = runSiteData.getDataH6();
		String dH7 = runSiteData.getDataH7();
		String dH8 = runSiteData.getDataH8();
		String dH9 = runSiteData.getDataH9();
		String dH10 = runSiteData.getDataH10();
		String dH11 = runSiteData.getDataH11();
		String dH12 = runSiteData.getDataH12();
		String dH13 = runSiteData.getDataH13();
		String dH14 = runSiteData.getDataH14();
		String dH15 = runSiteData.getDataH15();
		String dH16 = runSiteData.getDataH16();
		String dH17 = runSiteData.getDataH17();
		String dH18 = runSiteData.getDataH18();
		String dH19 = runSiteData.getDataH19();
		String dH20 = runSiteData.getDataH20();
		String dH21 = runSiteData.getDataH21();
		String dH22 = runSiteData.getDataH22();
		String dH23 = runSiteData.getDataH23();

		if (StringUtils.isBlank(dH0)) {
			hour--;
			dH0 = "0";
		}
		if (StringUtils.isBlank(dH1)) {
			hour--;
			dH1 = "0";
		}
		if (StringUtils.isBlank(dH2)) {
			hour--;
			dH2 = "0";
		}
		if (StringUtils.isBlank(dH3)) {
			hour--;
			dH3 = "0";
		}
		if (StringUtils.isBlank(dH4)) {
			hour--;
			dH4 = "0";
		}
		if (StringUtils.isBlank(dH5)) {
			hour--;
			dH5 = "0";
		}
		if (StringUtils.isBlank(dH6)) {
			hour--;
			dH6 = "0";
		}
		if (StringUtils.isBlank(dH7)) {
			hour--;
			dH7 = "0";
		}
		if (StringUtils.isBlank(dH8)) {
			hour--;
			dH8 = "0";
		}
		if (StringUtils.isBlank(dH9)) {
			hour--;
			dH9 = "0";
		}
		if (StringUtils.isBlank(dH10)) {
			hour--;
			dH10 = "0";
		}
		if (StringUtils.isBlank(dH11)) {
			hour--;
			dH11 = "0";
		}
		if (StringUtils.isBlank(dH12)) {
			hour--;
			dH12 = "0";
		}
		if (StringUtils.isBlank(dH13)) {
			hour--;
			dH13 = "0";
		}
		if (StringUtils.isBlank(dH14)) {
			hour--;
			dH14 = "0";
		}
		if (StringUtils.isBlank(dH15)) {
			hour--;
			dH15 = "0";
		}
		if (StringUtils.isBlank(dH16)) {
			hour--;
			dH16 = "0";
		}
		if (StringUtils.isBlank(dH17)) {
			hour--;
			dH17 = "0";
		}
		if (StringUtils.isBlank(dH18)) {
			hour--;
			dH18 = "0";
		}
		if (StringUtils.isBlank(dH19)) {
			hour--;
			dH19 = "0";
		}
		if (StringUtils.isBlank(dH20)) {
			hour--;
			dH20 = "0";
		}
		if (StringUtils.isBlank(dH21)) {
			hour--;
			dH21 = "0";
		}
		if (StringUtils.isBlank(dH22)) {
			hour--;
			dH22 = "0";
		}
		if (StringUtils.isBlank(dH23)) {
			hour--;
			dH23 = "0";
		}
		double d = 0;
		if (hour != 0) {
			d = ((Double.parseDouble(dH0) + Double.parseDouble(dH1) + Double.parseDouble(dH2) + Double.parseDouble(dH3)
					+ Double.parseDouble(dH4) + Double.parseDouble(dH5) + Double.parseDouble(dH6)
					+ Double.parseDouble(dH7) + Double.parseDouble(dH8) + Double.parseDouble(dH9)
					+ Double.parseDouble(dH10) + Double.parseDouble(dH11) + Double.parseDouble(dH12)
					+ Double.parseDouble(dH13) + Double.parseDouble(dH14) + Double.parseDouble(dH15)
					+ Double.parseDouble(dH16) + Double.parseDouble(dH17) + Double.parseDouble(dH18)
					+ Double.parseDouble(dH19) + Double.parseDouble(dH20) + Double.parseDouble(dH21)
					+ Double.parseDouble(dH22) + Double.parseDouble(dH23)) / hour) / 100;
		}
		DecimalFormat df = new DecimalFormat("0000.000");
		String format = df.format(d);
		return format;

	}

	private String getAvgPcp(RunSiteData runSiteData) {
		double hour = 24;
		String dH0 = runSiteData.getDataH0();
		String dH1 = runSiteData.getDataH1();
		String dH2 = runSiteData.getDataH2();
		String dH3 = runSiteData.getDataH3();
		String dH4 = runSiteData.getDataH4();
		String dH5 = runSiteData.getDataH5();
		String dH6 = runSiteData.getDataH6();
		String dH7 = runSiteData.getDataH7();
		String dH8 = runSiteData.getDataH8();
		String dH9 = runSiteData.getDataH9();
		String dH10 = runSiteData.getDataH10();
		String dH11 = runSiteData.getDataH11();
		String dH12 = runSiteData.getDataH12();
		String dH13 = runSiteData.getDataH13();
		String dH14 = runSiteData.getDataH14();
		String dH15 = runSiteData.getDataH15();
		String dH16 = runSiteData.getDataH16();
		String dH17 = runSiteData.getDataH17();
		String dH18 = runSiteData.getDataH18();
		String dH19 = runSiteData.getDataH19();
		String dH20 = runSiteData.getDataH20();
		String dH21 = runSiteData.getDataH21();
		String dH22 = runSiteData.getDataH22();
		String dH23 = runSiteData.getDataH23();
		if (StringUtils.isBlank(dH0)||dH0.equals("0.0")) {
			hour--;
			dH0 = "0";
		}
		if (StringUtils.isBlank(dH1)||dH1.equals("0.0")) {
			hour--;
			dH1 = "0";
		}
		if (StringUtils.isBlank(dH2)||dH2.equals("0.0")) {
			hour--;
			dH2 = "0";
		}
		if (StringUtils.isBlank(dH3)||dH3.equals("0.0")) {
			hour--;
			dH3 = "0";
		}
		if (StringUtils.isBlank(dH4)||dH4.equals("0.0")) {
			hour--;
			dH4 = "0";
		}
		if (StringUtils.isBlank(dH5)||dH5.equals("0.0")) {
			hour--;
			dH5 = "0";
		}
		if (StringUtils.isBlank(dH6)||dH6.equals("0.0")) {
			hour--;
			dH6 = "0";
		}
		if (StringUtils.isBlank(dH7)||dH7.equals("0.0")) {
			hour--;
			dH7 = "0";
		}
		if (StringUtils.isBlank(dH8)||dH8.equals("0.0")) {
			hour--;
			dH8 = "0";
		}
		if (StringUtils.isBlank(dH9)||dH9.equals("0.0")) {
			hour--;
			dH9 = "0";
		}
		if (StringUtils.isBlank(dH10)||dH10.equals("0.0")) {
			hour--;
			dH10 = "0";
		}
		if (StringUtils.isBlank(dH11)||dH11.equals("0.0")) {
			hour--;
			dH11 = "0";
		}
		if (StringUtils.isBlank(dH12)||dH12.equals("0.0")) {
			hour--;
			dH12 = "0";
		}
		if (StringUtils.isBlank(dH13)||dH13.equals("0.0")) {
			hour--;
			dH13 = "0";
		}
		if (StringUtils.isBlank(dH14)||dH14.equals("0.0")) {
			hour--;
			dH14 = "0";
		}
		if (StringUtils.isBlank(dH15)||dH15.equals("0.0")) {
			hour--;
			dH15 = "0";
		}
		if (StringUtils.isBlank(dH16)||dH16.equals("0.0")) {
			hour--;
			dH16 = "0";
		}
		if (StringUtils.isBlank(dH17)||dH17.equals("0.0")) {
			hour--;
			dH17 = "0";
		}
		if (StringUtils.isBlank(dH18)||dH18.equals("0.0")) {
			hour--;
			dH18 = "0";
		}
		if (StringUtils.isBlank(dH19)||dH19.equals("0.0")) {
			hour--;
			dH19 = "0";
		}
		if (StringUtils.isBlank(dH20)||dH20.equals("0.0")) {
			hour--;
			dH20 = "0";
		}
		if (StringUtils.isBlank(dH21)||dH21.equals("0.0")) {
			hour--;
			dH21 = "0";
		}
		if (StringUtils.isBlank(dH22)||dH22.equals("0.0")) {
			hour--;
			dH22 = "0";
		}
		if (StringUtils.isBlank(dH23)||dH23.equals("0.0")) {
			hour--;
			dH23 = "0";
		}
		/*if (StringUtils.isBlank(dH0)) {
			hour--;
			dH0 = "0";
		}
		if (StringUtils.isBlank(dH1)) {
			hour--;
			dH1 = "0";
		}
		if (StringUtils.isBlank(dH2)) {
			hour--;
			dH2 = "0";
		}
		if (StringUtils.isBlank(dH3)) {
			hour--;
			dH3 = "0";
		}
		if (StringUtils.isBlank(dH4)) {
			hour--;
			dH4 = "0";
		}
		if (StringUtils.isBlank(dH5)) {
			hour--;
			dH5 = "0";
		}
		if (StringUtils.isBlank(dH6)) {
			hour--;
			dH6 = "0";
		}
		if (StringUtils.isBlank(dH7)) {
			hour--;
			dH7 = "0";
		}
		if (StringUtils.isBlank(dH8)) {
			hour--;
			dH8 = "0";
		}
		if (StringUtils.isBlank(dH9)) {
			hour--;
			dH9 = "0";
		}
		if (StringUtils.isBlank(dH10)) {
			hour--;
			dH10 = "0";
		}
		if (StringUtils.isBlank(dH11)) {
			hour--;
			dH11 = "0";
		}
		if (StringUtils.isBlank(dH12)) {
			hour--;
			dH12 = "0";
		}
		if (StringUtils.isBlank(dH13)) {
			hour--;
			dH13 = "0";
		}
		if (StringUtils.isBlank(dH14)) {
			hour--;
			dH14 = "0";
		}
		if (StringUtils.isBlank(dH15)) {
			hour--;
			dH15 = "0";
		}
		if (StringUtils.isBlank(dH16)) {
			hour--;
			dH16 = "0";
		}
		if (StringUtils.isBlank(dH17)) {
			hour--;
			dH17 = "0";
		}
		if (StringUtils.isBlank(dH18)) {
			hour--;
			dH18 = "0";
		}
		if (StringUtils.isBlank(dH19)) {
			hour--;
			dH19 = "0";
		}
		if (StringUtils.isBlank(dH20)) {
			hour--;
			dH20 = "0";
		}
		if (StringUtils.isBlank(dH21)) {
			hour--;
			dH21 = "0";
		}
		if (StringUtils.isBlank(dH22)) {
			hour--;
			dH22 = "0";
		}
		if (StringUtils.isBlank(dH23)) {
			hour--;
			dH23 = "0";
		}*/
		double d = 0;
		if (hour != 0) {
			d = (Double.parseDouble(dH0) + Double.parseDouble(dH1) + Double.parseDouble(dH2) + Double.parseDouble(dH3)
					+ Double.parseDouble(dH4) + Double.parseDouble(dH5) + Double.parseDouble(dH6)
					+ Double.parseDouble(dH7) + Double.parseDouble(dH8) + Double.parseDouble(dH9)
					+ Double.parseDouble(dH10) + Double.parseDouble(dH11) + Double.parseDouble(dH12)
					+ Double.parseDouble(dH13) + Double.parseDouble(dH14) + Double.parseDouble(dH15)
					+ Double.parseDouble(dH16) + Double.parseDouble(dH17) + Double.parseDouble(dH18)
					+ Double.parseDouble(dH19) + Double.parseDouble(dH20) + Double.parseDouble(dH21)
					+ Double.parseDouble(dH22) + Double.parseDouble(dH23)) / hour;
		}

		DecimalFormat df = new DecimalFormat("000.0");
		String format = df.format(d);
		return format;

	}

	/**
	 * 计算风速24H 的平均值
	 * 
	 * @param runSiteData [0.6,44]
	 * @return
	 */
	private String getAvgWnd(RunSiteData runSiteData) {

		// 今天数据
//		if(DateUtil.dateToString(runSiteData.getDataTime()).equals(new Date())) {
//			
//		}	
		double hour = 24;
		String dH0 = runSiteData.getDataH0();
		String dH1 = runSiteData.getDataH1();
		String dH2 = runSiteData.getDataH2();
		String dH3 = runSiteData.getDataH3();
		String dH4 = runSiteData.getDataH4();
		String dH5 = runSiteData.getDataH5();
		String dH6 = runSiteData.getDataH6();
		String dH7 = runSiteData.getDataH7();
		String dH8 = runSiteData.getDataH8();
		String dH9 = runSiteData.getDataH9();
		String dH10 = runSiteData.getDataH10();
		String dH11 = runSiteData.getDataH11();
		String dH12 = runSiteData.getDataH12();
		String dH13 = runSiteData.getDataH13();
		String dH14 = runSiteData.getDataH14();
		String dH15 = runSiteData.getDataH15();
		String dH16 = runSiteData.getDataH16();
		String dH17 = runSiteData.getDataH17();
		String dH18 = runSiteData.getDataH18();
		String dH19 = runSiteData.getDataH19();
		String dH20 = runSiteData.getDataH20();
		String dH21 = runSiteData.getDataH21();
		String dH22 = runSiteData.getDataH22();
		String dH23 = runSiteData.getDataH23();

		if (StringUtils.isBlank(dH0)) {
			hour--;
			dH0 = "00.0";
		}
		if (StringUtils.isBlank(dH1)) {
			hour--;
			dH1 = "00.0";
		}
		if (StringUtils.isBlank(dH2)) {
			hour--;
			dH2 = "00.0";
		}
		if (StringUtils.isBlank(dH3)) {
			hour--;
			dH3 = "00.0";
		}
		if (StringUtils.isBlank(dH4)) {
			hour--;
			dH4 = "00.0";
		}
		if (StringUtils.isBlank(dH5)) {
			hour--;
			dH5 = "00.0";
		}
		if (StringUtils.isBlank(dH6)) {
			hour--;
			dH6 = "00.0";
		}
		if (StringUtils.isBlank(dH7)) {
			hour--;
			dH7 = "00.0";
		}
		if (StringUtils.isBlank(dH8)) {
			hour--;
			dH8 = "00.0";
		}
		if (StringUtils.isBlank(dH9)) {
			hour--;
			dH9 = "00.0";
		}
		if (StringUtils.isBlank(dH10)) {
			hour--;
			dH10 = "00.0";
		}
		if (StringUtils.isBlank(dH11)) {
			hour--;
			dH11 = "00.0";
		}
		if (StringUtils.isBlank(dH12)) {
			hour--;
			dH12 = "00.0";
		}
		if (StringUtils.isBlank(dH13)) {
			hour--;
			dH13 = "00.0";
		}
		if (StringUtils.isBlank(dH14)) {
			hour--;
			dH14 = "00.0";
		}
		if (StringUtils.isBlank(dH15)) {
			hour--;
			dH15 = "00.0";
		}
		if (StringUtils.isBlank(dH16)) {
			hour--;
			dH16 = "00.0";
		}
		if (StringUtils.isBlank(dH17)) {
			hour--;
			dH17 = "00.0";
		}
		if (StringUtils.isBlank(dH18)) {
			hour--;
			dH18 = "00.0";
		}
		if (StringUtils.isBlank(dH19)) {
			hour--;
			dH19 = "00.0";
		}
		if (StringUtils.isBlank(dH20)) {
			hour--;
			dH20 = "00.0";
		}
		if (StringUtils.isBlank(dH21)) {
			hour--;
			dH21 = "00.0";
		}
		if (StringUtils.isBlank(dH22)) {
			hour--;
			dH22 = "00.0";
		}
		if (StringUtils.isBlank(dH23)) {
			hour--;
			dH23 = "00.0";
		}

		String s0 = dH0.substring(1, 4);
		String s1 = dH1.substring(1, 4);
		String s2 = dH2.substring(1, 4);
		String s3 = dH3.substring(1, 4);
		String s4 = dH4.substring(1, 4);
		String s5 = dH5.substring(1, 4);
		String s6 = dH6.substring(1, 4);
		String s7 = dH7.substring(1, 4);
		String s8 = dH8.substring(1, 4);
		String s9 = dH9.substring(1, 4);
		String s10 = dH10.substring(1, 4);
		String s11 = dH11.substring(1, 4);
		String s12 = dH12.substring(1, 4);
		String s13 = dH13.substring(1, 4);
		String s14 = dH14.substring(1, 4);
		String s15 = dH15.substring(1, 4);
		String s16 = dH16.substring(1, 4);
		String s17 = dH17.substring(1, 4);
		String s18 = dH18.substring(1, 4);
		String s19 = dH19.substring(1, 4);
		String s20 = dH20.substring(1, 4);
		String s21 = dH21.substring(1, 4);
		String s22 = dH22.substring(1, 4);
		String s23 = dH23.substring(1, 4);
		double d = 0;
		if (hour != 0) {
			d = (Double.parseDouble(s0) + Double.parseDouble(s1) + Double.parseDouble(s2) + Double.parseDouble(s3)
					+ Double.parseDouble(s4) + Double.parseDouble(s5) + Double.parseDouble(s6) + Double.parseDouble(s7)
					+ Double.parseDouble(s8) + Double.parseDouble(s9) + Double.parseDouble(s10)
					+ Double.parseDouble(s11) + Double.parseDouble(s12) + Double.parseDouble(s13)
					+ Double.parseDouble(s14) + Double.parseDouble(s15) + Double.parseDouble(s16)
					+ Double.parseDouble(s17) + Double.parseDouble(s18) + Double.parseDouble(s19)
					+ Double.parseDouble(s20) + Double.parseDouble(s21) + Double.parseDouble(s22)
					+ Double.parseDouble(s23)) / hour;
		}
		DecimalFormat df = new DecimalFormat("0000.000");
		String format = df.format(d);
		return format;
	}

	/**
	 * 水动力
	 */
	private void exNydro() {

		Runtime rn = Runtime.getRuntime();
		Process p = null;
		InputStream in = null;
		BufferedReader reader = null;
		try {
			System.out.println("执行开始 水动力—" + new Date());
			p = rn.exec(waterNydroPath);
			p.getOutputStream().close();
			in = p.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("执行结束 —" + new Date());

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 水质
	 */
	private void exSBW() {
		Runtime rn = Runtime.getRuntime();
		Process p = null;
		InputStream in = null;
		BufferedReader reader = null;
		try {
			System.out.println("执行开始水质 —" + new Date());
			p = rn.exec(waterSBWPath);
			p.getOutputStream().close();
			in = p.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("执行结束 —" + new Date());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 水流域
	 */
	private void exWater() {
		InputStream in = null;
		BufferedReader reader = null;
		Runtime rnWater = Runtime.getRuntime();
		Process p = null;
		try {
			System.out.println("开始执行水流域 —" + new Date());
			p = rnWater.exec(waterPath);
			p.getOutputStream().close();
			in = p.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("执行结束 —" + new Date());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 校验文件 true 无该文件 12 水流域输入 输出 34 水动力 56 水质
	 * 
	 * @param fileName
	 * @return
	 */
	private int checkFileName(String fileName) {
		Map<String, Integer> fileNameMap = new HashedMap();
		// 1 2 流域输入输出 34 水动力 56 水质
		fileNameMap.put("file.cio", 1);
		fileNameMap.put("fig.fig", 1);
		fileNameMap.put("basins.bsn", 1);
		fileNameMap.put("pcp1.pcp", 1);
		fileNameMap.put("Tmp1.Tmpp", 1);
		fileNameMap.put(".slr", 1);
		fileNameMap.put("wnd.wnd", 1);
		fileNameMap.put("hmd.hmd", 1);
		fileNameMap.put(".pet", 1);
		fileNameMap.put("cst.cst", 1);
		fileNameMap.put(".cal", 1);
		fileNameMap.put("crop.dat", 1);
		fileNameMap.put("till.dat", 1);
		fileNameMap.put("pest.dat", 1);
		fileNameMap.put("fert.dat", 1);
		fileNameMap.put("urban.dat", 1);
		fileNameMap.put("septic.dat", 1);
		fileNameMap.put(".sub", 1);
		fileNameMap.put(".wgn", 1);
		fileNameMap.put(".pnd", 1);
		fileNameMap.put(".wus", 1);
		fileNameMap.put(".rte", 1);
		fileNameMap.put(".sep", 1);
		fileNameMap.put("basins.wwq", 1);
		fileNameMap.put(".swq", 1);
		fileNameMap.put(".hru", 1);
		fileNameMap.put(".mgt", 1);
		fileNameMap.put(".sol", 1);
		fileNameMap.put(".chm", 1);
		fileNameMap.put(".gw", 1);
		fileNameMap.put(".res", 1);
		fileNameMap.put(".lwq", 1);
		fileNameMap.put("rechour.dat", 1);
		fileNameMap.put("recday.dat", 1);
		fileNameMap.put("recmon.dat", 1);
		fileNameMap.put("recyear.dat", 1);
		fileNameMap.put("reccnst.dat", 1);
		fileNameMap.put("44p.dat", 1);

		fileNameMap.put("bmp-ri.out", 2);
		fileNameMap.put("bmp-sedfil.out", 2);
		fileNameMap.put("chan.deg", 2);
		fileNameMap.put("charles.out", 2);
		fileNameMap.put("fin.fin", 2);
		fileNameMap.put("hyd.out", 2);
		fileNameMap.put("input.std", 2);
		fileNameMap.put("output.hru", 2);
		fileNameMap.put("output.rch", 2);
		fileNameMap.put("output.rsv", 2);
		fileNameMap.put("output.sed", 2);
		fileNameMap.put("output.std", 2);
		fileNameMap.put("output.sub", 2);
		fileNameMap.put("septic.out", 2);
		fileNameMap.put("watout.dat", 2);

		fileNameMap.put("szb.bca", 3);
		fileNameMap.put("szb.res", 3);
		fileNameMap.put("szb.bcc", 3);
		fileNameMap.put("szb.bct", 3);
		fileNameMap.put("szb.bnd", 3);
		fileNameMap.put("szb.dep", 3);
		fileNameMap.put("szb.dis", 3);
		fileNameMap.put("szb.enc", 3);
		fileNameMap.put("szb.grd", 3);
		fileNameMap.put("szb.obs", 3);
		fileNameMap.put("szb.wnd", 3);
		fileNameMap.put("Ocean model.tem", 3);
		fileNameMap.put("big.wnd", 3);

		fileNameMap.put("com-szb.dat", 4);
		fileNameMap.put("com-szb.def", 4);
		fileNameMap.put("com-2221376bujiami.def", 4);
		fileNameMap.put("tri-diag.2221376bujiami", 4);
		fileNameMap.put("tri-prt.2221376bujiami", 4);
		fileNameMap.put("tri-rst.szb.20150103.000000", 4);
		fileNameMap.put("2221376bujiami", 4);
		fileNameMap.put("trih-szb.dat", 4);
		fileNameMap.put("trih-szb.def", 4);
		fileNameMap.put("trim-szb.dat", 4);
		fileNameMap.put("trim-szb.def", 4);
		fileNameMap.put("SB_boundary_update.dat", 5);
		fileNameMap.put("SB_coefficients_update.dat", 5);
		fileNameMap.put("SB_initial.ini", 5);
		fileNameMap.put("test2_res.map", 5);
		fileNameMap.put("SB_map_output.nam", 5);
		fileNameMap.put("SB_output.nam", 5);
		fileNameMap.put("SBW_2015-radsurf.dat", 5);
		fileNameMap.put("SBW_2015-wind.dat", 5);
		fileNameMap.put("SBW_river_loads_test2.dat", 5);
		fileNameMap.put("test2.inp", 5);

		fileNameMap.put("delwaq.rtn", 6);
		fileNameMap.put("fort.32", 6);
		fileNameMap.put("test2_r.his", 6);
		fileNameMap.put("test2_r.map", 6);
		fileNameMap.put("test2_r.mon", 6);
		fileNameMap.put("test2_r_res.map", 6);
		fileNameMap.put("test2_r-bal.his", 6);
		fileNameMap.put("test2_r-timers.out", 6);
		fileNameMap.put("bloominp.dbg", 6);
		fileNameMap.put("memory_map.out", 6);
		fileNameMap.put("test2_r.lsp", 6);
		fileNameMap.put("test2_r.lst", 6);
		fileNameMap.put("bloominp.frm", 6);
		fileNameMap.put("test2-bal.his", 6);
		fileNameMap.put("test2.his", 6);
		fileNameMap.put("test2.map", 6);
		fileNameMap.put("test2.mon", 6);
		fileNameMap.put("test2_res.map", 6);
		fileNameMap.put("test2-timers.out", 6);
		fileNameMap.put("test2.lsp", 6);
		fileNameMap.put("test2.lst", 6);
		fileNameMap.put("test2-initials.map", 6);

		if (null == fileNameMap.get(fileName)) {
			return 0;
		}
		return fileNameMap.get(fileName);
	}

	private static void getRows(String a, String b, int row1, int row2) {
		Map<Integer, String> row1_12 = FileUtil.getFileContent3(a, row1, row2);
		StringBuilder sb1 = new StringBuilder();
		for (Entry<Integer, String> m : row1_12.entrySet()) {
			// System.err.println(m.getKey() + "-----" + m.getValue());
			sb1.append(m.getValue());
			sb1.append("\n");
		}
		FileUtil.createFileOrWrite(b, sb1.toString());
	}

	private static void getRows2(String a, String b, int row1, int row2, List<String> list) {
		list.add(0, list.get(0));
		list.add(list.get(list.size() - 1));
		// 月
		int j = 0;
		StringBuilder sb = new StringBuilder();
		Map<Integer, String> row = FileUtil.getFileContent3(a, row1, row2);
		String tou = "";
		String wei = "";

		for (Entry<Integer, String> m : row.entrySet()) {

			// System.err.println(m.getKey()+"-----"+m.getValue());
			String value = m.getValue();

			String[] split = value.split(" ");
			int i = 1;

			/**
			 * 第一行和第二行 数据一样 第十三行和第十四行一样 不能执行模型 所以第一行和第十四行数据和旧的一样
			 */
//			if(m.getKey()==row1) {
//				String string2 = row.get(row1+1);
//			    split = string2.split(" ");
//				for (String string : split) {
//					if (StringUtils.isNotBlank(string)) {
//						// 第二列
//						if (i == 2) {
//							String str = list.get(j);
//							// 科学计数法 scientific(str)
//							tou+=scientific(str);
//						} else {
//							// 其他列保持不变 
//							tou+=string;
//						}
//						tou+="  ";
//						i++;
//					}
//				}
//				continue;
//			}
//			if(m.getKey()==row2) {
//				String string2 = row.get(row2-1);
//			    split = string2.split(" ");
//				for (String string : split) {
//					if (StringUtils.isNotBlank(string)) {
//						// 第二列
//						if (i == 2) {
//							String str = list.get(j);
//							// 科学计数法 scientific(str)
//							wei+=scientific(str);
//						} else {
//							// 其他列保持不变 
//							wei+=string;
//						}
//						wei+="  ";
//						i++;
//					}
//				}
//				continue;
//			}
			sb.append(" ");
			for (String string : split) {

				if (StringUtils.isNotBlank(string)) {
					// 第二列
					if (i == 2) {
						String str = list.get(j);
						// 科学计数法 scientific(str)

						sb.append(scientific(str));
						j++;
					} else {
						// 其他列保持不变 TODO
						sb.append(string);
					}
					sb.append("  ");
					i++;
				}
			}
			sb.append("\n");
		}
		// FileUtil.appendContent(b, " "+tou+"\n"+sb.toString()+" "+wei);
		FileUtil.appendContent(b, sb.toString().substring(0, sb.toString().length() - 1));
	}

	private static String scientific(String str) {

		String res = "0.0000000e+000";
		double dStr = Double.parseDouble(str);
		DecimalFormat df = new DecimalFormat("#0.00");

		if (dStr >= 1000 && dStr < 10000) {
			res = df.format(dStr / 1000) + "00000e+003";
		} else if (dStr >= 100 && dStr < 1000) {
			res = df.format(dStr / 100) + "00000e+002";
		} else if (dStr >= 10 && dStr < 100) {
			res = df.format(dStr / 10) + "00000e+001";
		} else if (dStr >= 1 && dStr < 10) {
			res = df.format(dStr) + "00000e+000";
		} else if (dStr >= 0.1 && dStr < 1) {
			res = df.format(dStr * 10) + "00000e-001";
		} else if (dStr > 0.01 && dStr < 0.1) {
			res = df.format(dStr * 100) + "00000e-002";
		} else if (dStr > 0.001 && dStr < 0.01) {
			res = df.format(dStr * 1000) + "00000e-003";
		} else if (dStr > 0.0001 && dStr < 0.001) {
			res = df.format(dStr * 10000) + "00000e-004";
		} else if (dStr > 0.00001 && dStr < 0.0001) {
			res = df.format(dStr * 100000) + "00000e-005";
		}
		return res;
	}

	private static void getRows1(String a, String b, int row1, int row2) {
		StringBuilder sb = new StringBuilder();
		Map<Integer, String> row = FileUtil.getFileContent3(a, row1, row2);
		for (Entry<Integer, String> m : row.entrySet()) {
			// System.err.println(m.getKey() + "-----" + m.getValue());
			sb.append(m.getValue());
			sb.append("\n");

		}
		FileUtil.appendContent(b, sb.toString().substring(0, sb.toString().length() - 1));
	}

	/**
	 * 删除 水质模型执行的记录
	 */
	@RequestMapping("deleteMap.do")
	public void deleteSuiZhi(String mapName) {
		// 20201010090542_test2_r.map
		if (StringUtils.isBlank(mapName)) {
			return;
		}
		String[] split = mapName.split("_");
		String tou = split[0];
		List<RunFilePath> list = runFilePathrService.findByMapAll();
		if (CollectionUtils.isNotEmpty(list)) {
			for (RunFilePath runFilePath : list) {
				String fileName = runFilePath.getFileName();
				if (!fileName.startsWith(tou)) {
					continue;
				}
				if (fileName.contains("output.rch") || (fileName.contains("r-bal.his"))
						|| fileName.contains("trih-szb.dat") || fileName.contains("trim-szb.dat")) {
					runFilePathrService.delById(runFilePath.getId());
					File f = new File(runFilePath.getFilePath() + fileName);
					if (f.exists()) {
						f.delete();
					}
					continue;
				}

				// 删除map数据库数据 5 个表
				if (fileName.endsWith(".map")) {
					runMapDataService.deleteByMapId(runFilePath.getId());

					List<RunMapPic> findByMapName2 = runMapPicService.findByMapName(fileName);
					if (CollectionUtils.isNotEmpty(findByMapName2)) {
						// 删除 pic
						FileUtil.deleteFiles(findByMapName2.get(0).getMapPicPath());
						File f = new File(findByMapName2.get(0).getMapPicPath());
						f.delete();
						runMapPicService.delByMapName(fileName);
					}
					// 删除png

					List<RunMapPic> findByMapName3 = runMapPicService.findByMapNamePng(fileName);
					if (CollectionUtils.isNotEmpty(findByMapName3)) {

						FileUtil.deleteFiles(findByMapName3.get(0).getMapPicPath());
						File f = new File(findByMapName3.get(0).getMapPicPath());
						if (f.exists()) {
							f.delete();
						}
						runMapPicService.delByMapNamePng(fileName);
					}
					
					runFilePathrService.delById(runFilePath.getId());
					continue;
				}
				if (fileName.endsWith("r.his")) {
					sysHearWordService.delById(runFilePath.getId());
					runFilePathrService.delById(runFilePath.getId());
				}
			}
		}

	}

	/**
	 * TODO 测试map转数据的类 测完坐标后删除
	 */
	@RequestMapping(value="test.do",method = RequestMethod.POST)
	@ResponseBody
	public String 测试map数据(String data,String startDate,String endDate) {
		System.out.println("data======"+data);
		System.out.println("startDate======"+startDate);
		System.out.println("endDate======"+endDate);
		return data;
//		测试定时任务("测试定时任务立即执行一次", null, null);
//		String fileName = "20201106145416_test2_r.map";
//		List<RunMapPic> findByMapName3 = runMapPicService.findByMapNamePng(fileName);
//		if (CollectionUtils.isNotEmpty(findByMapName3)) {
//
//			FileUtil.deleteFiles(findByMapName3.get(0).getMapPicPath());
//			File f = new File(findByMapName3.get(0).getMapPicPath());
//			if (f.exists()) {
//				f.delete();
//			}
//			runMapPicService.delByMapNamePng(fileName);
//		}
//
//		runFilePathrService.delById("41ff732c4ea54c57afd085ce4920b7d4");
	}
}